Skip to content

Commit b309779

Browse files
committed
CLOUDSTACK-8701: Add listandswitchsamlaccount API test and add boundary checks
- Adds unit test for ListAndSwitchSAMLAccountCmd - Checks and logs in user only if they are enabled - If saml user switches to a locked account, send appropriate error message Signed-off-by: Rohit Yadav <rohit.yadav@shapeblue.com>
1 parent 3c9d1fd commit b309779

3 files changed

Lines changed: 231 additions & 15 deletions

File tree

‎plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/ListAndSwitchSAMLAccountCmd.java‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import com.cloud.api.response.ApiResponseSerializer;
2020
import com.cloud.domain.Domain;
2121
import com.cloud.domain.dao.DomainDao;
22+
import com.cloud.exception.CloudAuthenticationException;
2223
import com.cloud.user.Account;
2324
import com.cloud.user.User;
2425
import com.cloud.user.UserAccount;
@@ -50,6 +51,7 @@
5051
import javax.servlet.http.HttpServletRequest;
5152
import javax.servlet.http.HttpServletResponse;
5253
import javax.servlet.http.HttpSession;
54+
import java.io.IOException;
5355
import java.util.ArrayList;
5456
import java.util.List;
5557
import java.util.Map;
@@ -131,7 +133,14 @@ public String authenticate(final String command, final Map<String, Object[]> par
131133
final User user = _userDao.findByUuid(userUuid);
132134
final Domain domain = _domainDao.findByUuid(domainUuid);
133135
final UserAccount nextUserAccount = _accountService.getUserAccountById(user.getId());
134-
if (!nextUserAccount.getUsername().equals(currentUserAccount.getUsername())
136+
if (nextUserAccount != null && !nextUserAccount.getAccountState().equals(Account.State.enabled.toString())) {
137+
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(),
138+
"The requested user account is locked and cannot be switched to, please contact your administrator.",
139+
params, responseType));
140+
}
141+
if (nextUserAccount == null
142+
|| !nextUserAccount.getAccountState().equals(Account.State.enabled.toString())
143+
|| !nextUserAccount.getUsername().equals(currentUserAccount.getUsername())
135144
|| !nextUserAccount.getExternalEntity().equals(currentUserAccount.getExternalEntity())
136145
|| (nextUserAccount.getDomainId() != domain.getId())
137146
|| (nextUserAccount.getSource() != User.Source.SAML2)) {
@@ -147,7 +156,8 @@ public String authenticate(final String command, final Map<String, Object[]> par
147156
resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
148157
return ApiResponseSerializer.toSerializedString(loginResponse, responseType);
149158
}
150-
} catch (final Exception ignored) {
159+
} catch (CloudAuthenticationException | IOException exception) {
160+
s_logger.debug("Failed to switch to request SAML user account due to: " + exception.getMessage());
151161
}
152162
} else {
153163
List<UserAccountVO> switchableAccounts = _userAccountDao.getAllUsersByNameAndEntity(currentUserAccount.getUsername(), currentUserAccount.getExternalEntity());

‎plugins/user-authenticators/saml2/src/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmd.java‎

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.apache.cloudstack.api.command;
1818

1919
import com.cloud.api.response.ApiResponseSerializer;
20+
import com.cloud.exception.CloudAuthenticationException;
2021
import com.cloud.user.Account;
2122
import com.cloud.user.DomainManager;
2223
import com.cloud.user.UserAccount;
@@ -290,28 +291,32 @@ public String authenticate(final String command, final Map<String, Object[]> par
290291
UserAccount userAccount = null;
291292
List<UserAccountVO> possibleUserAccounts = _userAccountDao.getAllUsersByNameAndEntity(username, issuer.getValue());
292293
if (possibleUserAccounts != null && possibleUserAccounts.size() > 0) {
293-
// By default, log into the first user account
294+
// Log into the first enabled user account
294295
// Users can switch to other allowed accounts later
295-
userAccount = possibleUserAccounts.get(0);
296+
for (UserAccountVO possibleUserAccount: possibleUserAccounts) {
297+
if (possibleUserAccount.getAccountState().equals(Account.State.enabled.toString())) {
298+
userAccount = possibleUserAccount;
299+
break;
300+
}
301+
}
296302
}
297303

298304
if (userAccount == null || userAccount.getExternalEntity() == null || !_samlAuthManager.isUserAuthorized(userAccount.getId(), issuer.getValue())) {
299305
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(),
300-
"Your authenticated user is not authorized, please contact your administrator",
306+
"Your authenticated user is not authorized for SAML Single Sign-On, please contact your administrator",
301307
params, responseType));
302308
}
303309

304-
if (userAccount != null) {
305-
try {
306-
if (_apiServer.verifyUser(userAccount.getId())) {
307-
LoginCmdResponse loginResponse = (LoginCmdResponse) _apiServer.loginUser(session, userAccount.getUsername(), userAccount.getUsername() + userAccount.getSource().toString(),
308-
userAccount.getDomainId(), null, remoteAddress, params);
309-
SAMLUtils.setupSamlUserCookies(loginResponse, resp);
310-
resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
311-
return ApiResponseSerializer.toSerializedString(loginResponse, responseType);
312-
}
313-
} catch (final Exception ignored) {
310+
try {
311+
if (_apiServer.verifyUser(userAccount.getId())) {
312+
LoginCmdResponse loginResponse = (LoginCmdResponse) _apiServer.loginUser(session, userAccount.getUsername(), userAccount.getUsername() + userAccount.getSource().toString(),
313+
userAccount.getDomainId(), null, remoteAddress, params);
314+
SAMLUtils.setupSamlUserCookies(loginResponse, resp);
315+
resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
316+
return ApiResponseSerializer.toSerializedString(loginResponse, responseType);
314317
}
318+
} catch (CloudAuthenticationException | IOException exception) {
319+
s_logger.debug("SAML Login failed to log in the user due to: " + exception.getMessage());
315320
}
316321
}
317322
} catch (IOException e) {
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one
3+
* or more contributor license agreements. See the NOTICE file
4+
* distributed with this work for additional information
5+
* regarding copyright ownership. The ASF licenses this file
6+
* to you under the Apache License, Version 2.0 (the
7+
* "License"); you may not use this file except in compliance
8+
* with the License. You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
package org.apache.cloudstack.api.command;
21+
22+
import com.cloud.domain.DomainVO;
23+
import com.cloud.domain.dao.DomainDao;
24+
import com.cloud.user.Account;
25+
import com.cloud.user.AccountService;
26+
import com.cloud.user.User;
27+
import com.cloud.user.UserAccountVO;
28+
import com.cloud.user.UserVO;
29+
import com.cloud.user.dao.UserAccountDao;
30+
import com.cloud.user.dao.UserDao;
31+
import com.cloud.utils.HttpUtils;
32+
import junit.framework.TestCase;
33+
import org.apache.cloudstack.api.ApiConstants;
34+
import org.apache.cloudstack.api.ApiErrorCode;
35+
import org.apache.cloudstack.api.ApiServerService;
36+
import org.apache.cloudstack.api.BaseCmd;
37+
import org.apache.cloudstack.api.ServerApiException;
38+
import org.apache.cloudstack.api.auth.APIAuthenticationType;
39+
import org.apache.cloudstack.api.response.LoginCmdResponse;
40+
import org.apache.cloudstack.saml.SAML2AuthManager;
41+
import org.junit.Assert;
42+
import org.junit.Test;
43+
import org.junit.runner.RunWith;
44+
import org.mockito.Mock;
45+
import org.mockito.Mockito;
46+
import org.mockito.runners.MockitoJUnitRunner;
47+
48+
import javax.servlet.http.HttpServletRequest;
49+
import javax.servlet.http.HttpServletResponse;
50+
import javax.servlet.http.HttpSession;
51+
import java.lang.reflect.Field;
52+
import java.util.HashMap;
53+
import java.util.Map;
54+
55+
@RunWith(MockitoJUnitRunner.class)
56+
public class ListAndSwitchSAMLAccountCmdTest extends TestCase {
57+
@Mock
58+
ApiServerService apiServer;
59+
60+
@Mock
61+
SAML2AuthManager samlAuthManager;
62+
63+
@Mock
64+
AccountService accountService;
65+
66+
@Mock
67+
UserAccountDao userAccountDao;
68+
69+
@Mock
70+
UserDao userDao;
71+
72+
@Mock
73+
DomainDao domainDao;
74+
75+
@Mock
76+
HttpSession session;
77+
78+
@Mock
79+
HttpServletResponse resp;
80+
81+
@Mock
82+
HttpServletRequest req;
83+
84+
@Test
85+
public void testListAndSwitchSAMLAccountCmd() throws Exception {
86+
// Setup
87+
final Map<String, Object[]> params = new HashMap<String, Object[]>();
88+
final String sessionKeyValue = "someSessionIDValue";
89+
Mockito.when(session.getAttribute(ApiConstants.SESSIONKEY)).thenReturn(sessionKeyValue);
90+
Mockito.when(session.getAttribute("userid")).thenReturn(2L);
91+
params.put(ApiConstants.USER_ID, new String[]{"2"});
92+
params.put(ApiConstants.DOMAIN_ID, new String[]{"1"});
93+
Mockito.when(userDao.findByUuid(Mockito.anyString())).thenReturn(new UserVO(2L));
94+
Mockito.when(domainDao.findByUuid(Mockito.anyString())).thenReturn(new DomainVO());
95+
96+
// Mock/field setup
97+
ListAndSwitchSAMLAccountCmd cmd = new ListAndSwitchSAMLAccountCmd();
98+
Field apiServerField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_apiServer");
99+
apiServerField.setAccessible(true);
100+
apiServerField.set(cmd, apiServer);
101+
102+
Field managerField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_samlAuthManager");
103+
managerField.setAccessible(true);
104+
managerField.set(cmd, samlAuthManager);
105+
106+
Field accountServiceField = BaseCmd.class.getDeclaredField("_accountService");
107+
accountServiceField.setAccessible(true);
108+
accountServiceField.set(cmd, accountService);
109+
110+
Field userAccountDaoField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_userAccountDao");
111+
userAccountDaoField.setAccessible(true);
112+
userAccountDaoField.set(cmd, userAccountDao);
113+
114+
Field userDaoField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_userDao");
115+
userDaoField.setAccessible(true);
116+
userDaoField.set(cmd, userDao);
117+
118+
Field domainDaoField = ListAndSwitchSAMLAccountCmd.class.getDeclaredField("_domainDao");
119+
domainDaoField.setAccessible(true);
120+
domainDaoField.set(cmd, domainDao);
121+
122+
// invalid session test
123+
try {
124+
cmd.authenticate("command", params, null, "random", HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
125+
} catch (ServerApiException exception) {
126+
assertEquals(exception.getErrorCode(), ApiErrorCode.UNAUTHORIZED);
127+
} finally {
128+
Mockito.verify(accountService, Mockito.times(0)).getUserAccountById(Mockito.anyLong());
129+
}
130+
131+
// invalid sessionkey value test
132+
params.put(ApiConstants.SESSIONKEY, new String[]{"someOtherValue"});
133+
try {
134+
Mockito.when(session.isNew()).thenReturn(false);
135+
cmd.authenticate("command", params, session, "random", HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
136+
} catch (ServerApiException exception) {
137+
assertEquals(exception.getErrorCode(), ApiErrorCode.UNAUTHORIZED);
138+
} finally {
139+
Mockito.verify(accountService, Mockito.times(0)).getUserAccountById(Mockito.anyLong());
140+
}
141+
142+
// valid sessionkey value test
143+
params.put(ApiConstants.SESSIONKEY, new String[]{sessionKeyValue});
144+
try {
145+
cmd.authenticate("command", params, session, "random", HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
146+
} catch (ServerApiException exception) {
147+
assertEquals(exception.getErrorCode(), ApiErrorCode.ACCOUNT_ERROR);
148+
} finally {
149+
Mockito.verify(accountService, Mockito.times(1)).getUserAccountById(Mockito.anyLong());
150+
}
151+
152+
// valid sessionkey, invalid useraccount type (non-saml) value test
153+
UserAccountVO mockedUserAccount = new UserAccountVO();
154+
mockedUserAccount.setId(2L);
155+
mockedUserAccount.setAccountState(Account.State.enabled.toString());
156+
mockedUserAccount.setUsername("someUsername");
157+
mockedUserAccount.setExternalEntity("some IDP ID");
158+
mockedUserAccount.setDomainId(0L);
159+
mockedUserAccount.setSource(User.Source.UNKNOWN);
160+
Mockito.when(accountService.getUserAccountById(Mockito.anyLong())).thenReturn(mockedUserAccount);
161+
try {
162+
cmd.authenticate("command", params, session, "random", HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
163+
} catch (ServerApiException exception) {
164+
assertEquals(exception.getErrorCode(), ApiErrorCode.ACCOUNT_ERROR);
165+
} finally {
166+
// accountService should have been called twice by now, for this case and the case above
167+
Mockito.verify(accountService, Mockito.times(2)).getUserAccountById(Mockito.anyLong());
168+
}
169+
170+
// all valid test
171+
mockedUserAccount.setSource(User.Source.SAML2);
172+
Mockito.when(accountService.getUserAccountById(Mockito.anyLong())).thenReturn(mockedUserAccount);
173+
Mockito.when(apiServer.verifyUser(Mockito.anyLong())).thenReturn(true);
174+
LoginCmdResponse loginCmdResponse = new LoginCmdResponse();
175+
loginCmdResponse.setUserId("1");
176+
loginCmdResponse.setDomainId("1");
177+
loginCmdResponse.setType("1");
178+
loginCmdResponse.setUsername("userName");
179+
loginCmdResponse.setAccount("someAccount");
180+
loginCmdResponse.setFirstName("firstName");
181+
loginCmdResponse.setLastName("lastName");
182+
loginCmdResponse.setSessionKey("newSessionKeyString");
183+
Mockito.when(apiServer.loginUser(Mockito.any(HttpSession.class), Mockito.anyString(), Mockito.anyString(),
184+
Mockito.anyLong(), Mockito.anyString(), Mockito.anyString(), Mockito.anyMap())).thenReturn(loginCmdResponse);
185+
try {
186+
cmd.authenticate("command", params, session, "random", HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
187+
} catch (ServerApiException exception) {
188+
fail("SAML list and switch account API failed to pass for all valid data: " + exception.getMessage());
189+
} finally {
190+
// accountService should have been called 4 times by now, for this case twice and 2 for cases above
191+
Mockito.verify(accountService, Mockito.times(4)).getUserAccountById(Mockito.anyLong());
192+
Mockito.verify(resp, Mockito.times(1)).sendRedirect(Mockito.anyString());
193+
}
194+
}
195+
196+
@Test
197+
public void testGetAPIType() {
198+
Assert.assertTrue(new ListAndSwitchSAMLAccountCmd().getAPIType() == APIAuthenticationType.READONLY_API);
199+
}
200+
201+
}

0 commit comments

Comments
 (0)