Repository navigation
Expand file tree
/
Copy pathApiServerTest.java
More file actions
273 lines (229 loc) · 12.1 KB
/
Copy pathApiServerTest.java
File metadata and controls
273 lines (229 loc) · 12.1 KB
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
// 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 com.cloud.api;
import com.cloud.domain.Domain;
import com.cloud.exception.OriginDeniedException;
import com.cloud.exception.PermissionDeniedException;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.User;
import com.cloud.user.UserAccount;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.Pair;
import org.apache.cloudstack.config.ApiServiceConfiguration;
import org.apache.cloudstack.framework.config.ConfigKey;
import org.apache.cloudstack.framework.events.Event;
import org.apache.cloudstack.framework.events.EventDistributor;
import org.apache.cloudstack.framework.jobs.AsyncJob;
import org.apache.cloudstack.user.UserPasswordResetManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.apache.cloudstack.user.UserPasswordResetManager.UserPasswordResetEnabled;
@RunWith(MockitoJUnitRunner.class)
public class ApiServerTest {
@InjectMocks
ApiServer apiServer = new ApiServer();
@Mock
UserPasswordResetManager userPasswordResetManager;
@Mock
AccountManager accountMgr;
private static final String DEFAULT_CIDR_CHECKS_ENABLED = ApiServiceConfiguration.ApiSourceCidrChecksEnabled.defaultValue();
private static final String DEFAULT_ALLOWED_CIDRS = ApiServiceConfiguration.ApiAllowedSourceCidrList.defaultValue();
@BeforeClass
public static void beforeClass() throws Exception {
overrideDefaultConfigValue(UserPasswordResetEnabled, "_value", true);
}
@AfterClass
public static void afterClass() throws Exception {
overrideDefaultConfigValue(UserPasswordResetEnabled, "_value", false);
}
@Before
public void setupCommandAvailableChecks() {
apiServer.setApiAccessCheckers(Collections.emptyList());
}
@After
public void resetCidrConfig() throws Exception {
overrideDefaultConfigValue(ApiServiceConfiguration.ApiSourceCidrChecksEnabled, "_defaultValue", DEFAULT_CIDR_CHECKS_ENABLED);
overrideDefaultConfigValue(ApiServiceConfiguration.ApiAllowedSourceCidrList, "_defaultValue", DEFAULT_ALLOWED_CIDRS);
}
private static void overrideDefaultConfigValue(final ConfigKey configKey, final String name, final Object o) throws IllegalAccessException, NoSuchFieldException {
Field f = ConfigKey.class.getDeclaredField(name);
f.setAccessible(true);
f.set(configKey, o);
}
private void runTestSetupIntegrationPortListenerInvalidPorts(Integer port) {
try (MockedConstruction<ApiServer.ListenerThread> mocked =
Mockito.mockConstruction(ApiServer.ListenerThread.class)) {
apiServer.setupIntegrationPortListener(port);
Assert.assertTrue(mocked.constructed().isEmpty());
}
}
@Test
public void testSetupIntegrationPortListenerInvalidPorts() {
List<Integer> ports = new ArrayList<>(List.of(-1, -10, 0));
ports.add(null);
for (Integer port : ports) {
runTestSetupIntegrationPortListenerInvalidPorts(port);
}
}
@Test
public void testSetupIntegrationPortListenerValidPort() {
Integer validPort = 8080;
try (MockedConstruction<ApiServer.ListenerThread> mocked =
Mockito.mockConstruction(ApiServer.ListenerThread.class)) {
apiServer.setupIntegrationPortListener(validPort);
Assert.assertFalse(mocked.constructed().isEmpty());
ApiServer.ListenerThread listenerThread = mocked.constructed().get(0);
Mockito.verify(listenerThread).start();
}
}
@Test
public void testForgotPasswordSuccess() {
UserAccount userAccount = Mockito.mock(UserAccount.class);
Domain domain = Mockito.mock(Domain.class);
Mockito.when(userAccount.getEmail()).thenReturn("test@test.com");
Mockito.when(userAccount.getState()).thenReturn("ENABLED");
Mockito.when(userAccount.getAccountState()).thenReturn("ENABLED");
Mockito.when(domain.getState()).thenReturn(Domain.State.Active);
Mockito.doNothing().when(userPasswordResetManager).setResetTokenAndSend(userAccount);
Assert.assertTrue(apiServer.forgotPassword(userAccount, domain));
Mockito.verify(userPasswordResetManager).setResetTokenAndSend(userAccount);
}
@Test(expected = CloudRuntimeException.class)
public void testForgotPasswordFailureNoEmail() {
UserAccount userAccount = Mockito.mock(UserAccount.class);
Domain domain = Mockito.mock(Domain.class);
Mockito.when(userAccount.getEmail()).thenReturn("");
apiServer.forgotPassword(userAccount, domain);
}
@Test(expected = CloudRuntimeException.class)
public void testForgotPasswordFailureDisabledUser() {
UserAccount userAccount = Mockito.mock(UserAccount.class);
Domain domain = Mockito.mock(Domain.class);
Mockito.when(userAccount.getEmail()).thenReturn("test@test.com");
Mockito.when(userAccount.getState()).thenReturn("DISABLED");
apiServer.forgotPassword(userAccount, domain);
}
@Test(expected = CloudRuntimeException.class)
public void testForgotPasswordFailureDisabledAccount() {
UserAccount userAccount = Mockito.mock(UserAccount.class);
Domain domain = Mockito.mock(Domain.class);
Mockito.when(userAccount.getEmail()).thenReturn("test@test.com");
Mockito.when(userAccount.getState()).thenReturn("ENABLED");
Mockito.when(userAccount.getAccountState()).thenReturn("DISABLED");
apiServer.forgotPassword(userAccount, domain);
}
@Test(expected = CloudRuntimeException.class)
public void testForgotPasswordFailureInactiveDomain() {
UserAccount userAccount = Mockito.mock(UserAccount.class);
Domain domain = Mockito.mock(Domain.class);
Mockito.when(userAccount.getEmail()).thenReturn("test@test.com");
Mockito.when(userAccount.getState()).thenReturn("ENABLED");
Mockito.when(userAccount.getAccountState()).thenReturn("ENABLED");
Mockito.when(domain.getState()).thenReturn(Domain.State.Inactive);
apiServer.forgotPassword(userAccount, domain);
}
@Test
public void testVerifyApiKeyAccessAllowed() {
Long domainId = 1L;
User user = Mockito.mock(User.class);
Account account = Mockito.mock(Account.class);
Mockito.when(user.getApiKeyAccess()).thenReturn(true);
Assert.assertEquals(true, apiServer.verifyApiKeyAccessAllowed(user, account));
Mockito.verify(account, Mockito.never()).getApiKeyAccess();
Mockito.when(user.getApiKeyAccess()).thenReturn(false);
Assert.assertEquals(false, apiServer.verifyApiKeyAccessAllowed(user, account));
Mockito.verify(account, Mockito.never()).getApiKeyAccess();
Mockito.when(user.getApiKeyAccess()).thenReturn(null);
Mockito.when(account.getApiKeyAccess()).thenReturn(true);
Assert.assertEquals(true, apiServer.verifyApiKeyAccessAllowed(user, account));
Mockito.when(user.getApiKeyAccess()).thenReturn(null);
Mockito.when(account.getApiKeyAccess()).thenReturn(false);
Assert.assertEquals(false, apiServer.verifyApiKeyAccessAllowed(user, account));
Mockito.when(user.getApiKeyAccess()).thenReturn(null);
Mockito.when(account.getApiKeyAccess()).thenReturn(null);
Assert.assertEquals(true, apiServer.verifyApiKeyAccessAllowed(user, account));
}
@Test
public void testCheckCommandAvailableSkipsCidrLookupWhenDisabled() throws Exception {
overrideDefaultConfigValue(ApiServiceConfiguration.ApiSourceCidrChecksEnabled, "_defaultValue", "false");
User user = Mockito.mock(User.class);
ReflectionTestUtils.invokeMethod(apiServer, "checkCommandAvailable", user, "listVirtualMachines", InetAddress.getByName("127.0.0.1"));
Mockito.verify(accountMgr, Mockito.never()).getAccount(Mockito.anyLong());
}
@Test
public void testCheckCommandAvailableAllowsMatchingCidr() throws Exception {
overrideDefaultConfigValue(ApiServiceConfiguration.ApiSourceCidrChecksEnabled, "_defaultValue", "true");
overrideDefaultConfigValue(ApiServiceConfiguration.ApiAllowedSourceCidrList, "_defaultValue", "127.0.0.1/32");
User user = Mockito.mock(User.class);
Mockito.when(user.getAccountId()).thenReturn(1L);
Account account = Mockito.mock(Account.class);
Mockito.when(account.getId()).thenReturn(1L);
Mockito.when(accountMgr.getAccount(1L)).thenReturn(account);
ReflectionTestUtils.invokeMethod(apiServer, "checkCommandAvailable", user, "listVirtualMachines", InetAddress.getByName("127.0.0.1"));
Mockito.verify(accountMgr).getAccount(1L);
}
@Test(expected = OriginDeniedException.class)
public void testCheckCommandAvailableDeniesNonMatchingCidr() throws Exception {
overrideDefaultConfigValue(ApiServiceConfiguration.ApiSourceCidrChecksEnabled, "_defaultValue", "true");
overrideDefaultConfigValue(ApiServiceConfiguration.ApiAllowedSourceCidrList, "_defaultValue", "10.0.0.0/8");
User user = Mockito.mock(User.class);
Mockito.when(user.getAccountId()).thenReturn(1L);
Account account = Mockito.mock(Account.class);
Mockito.when(account.getId()).thenReturn(1L);
Mockito.when(accountMgr.getAccount(1L)).thenReturn(account);
ReflectionTestUtils.invokeMethod(apiServer, "checkCommandAvailable", user, "listVirtualMachines", InetAddress.getByName("127.0.0.1"));
}
@Test(expected = PermissionDeniedException.class)
public void testCheckCommandAvailableThrowsWhenUserNull() throws Exception {
ReflectionTestUtils.invokeMethod(apiServer, "checkCommandAvailable", null, "listVirtualMachines", InetAddress.getByName("127.0.0.1"));
}
@Test
public void handleAsyncJobPublishEventMasksSensitiveCmdInfo() {
AsyncJob job = Mockito.mock(AsyncJob.class);
Mockito.when(job.getDispatcher()).thenReturn("ApiAsyncJobDispatcher");
Mockito.when(job.getCmdInfo()).thenReturn("{\"userdata\":\"I2Nsb3VkLWNvbmZpZw==\",\"name\":\"vm1\"}");
User user = Mockito.mock(User.class);
Mockito.when(accountMgr.getUserIncludingRemoved(Mockito.anyLong())).thenReturn(user);
Mockito.when(accountMgr.getAccount(Mockito.anyLong())).thenReturn(Mockito.mock(Account.class));
EventDistributor eventDistributor = Mockito.mock(EventDistributor.class);
apiServer.setEventDistributor(eventDistributor);
apiServer.handleAsyncJobPublishEvent(null, null, new Pair<>(job, "test"));
ArgumentCaptor<Event> eventCaptor = ArgumentCaptor.forClass(Event.class);
Mockito.verify(eventDistributor).publish(eventCaptor.capture());
String description = eventCaptor.getValue().getDescription();
Assert.assertFalse(description.contains("I2Nsb3VkLWNvbmZpZw=="));
Assert.assertTrue(description.contains("vm1"));
}
}