Skip to content

Commit 12edad3

Browse files
committed
CLOUDSTACK-8622: Reinstate working sessions in browser
- Login is based on sessionkey HttpOnly Cookie - ApiServlet does login verification using sessionKey from both the request cookies and the API parameters. In both cases, if either or both are passed they should match the sessionKey stored in the current session of the HttpRequest - UI: it no longer needs to read or set sessionkey cookie - UI: it no longer needs to return g_sessionKey value in the API requests, though to support a sso mechanism g_sessionKey is still passed in the API is not null - Secure jsessionid cookie is set to be HttpOnly and Secure - SAML login should also set HttpOnly cookie before redirecting to UI - SAML: listIdps & getSPMetadata APIs are readonly now, won't log out a logged in user Performed tests (login, saml login if applicable, page refreshes, opening multiple tabs, logout) with following combinations: - SAML disabled, normal auth as admin, domain-admin and user - SAML enabled, normal auth as admin, domain-admin and user; and saml sso as admin, domain-admin and user Signed-off-by: Rohit Yadav <rohit.yadav@shapeblue.com> This closes apache#574 This closes apache#308
1 parent a2ddf27 commit 12edad3

11 files changed

Lines changed: 128 additions & 122 deletions

File tree

‎api/src/org/apache/cloudstack/api/auth/APIAuthenticationType.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,5 @@
1717
package org.apache.cloudstack.api.auth;
1818

1919
public enum APIAuthenticationType {
20-
LOGIN_API, LOGOUT_API
20+
LOGIN_API, LOGOUT_API, READONLY_API
2121
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ public String authenticate(String command, Map<String, Object[]> params, HttpSes
255255

256256
@Override
257257
public APIAuthenticationType getAPIType() {
258-
return APIAuthenticationType.LOGIN_API;
258+
return APIAuthenticationType.READONLY_API;
259259
}
260260

261261
@Override

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ public String authenticate(String command, Map<String, Object[]> params, HttpSes
9797

9898
@Override
9999
public APIAuthenticationType getAPIType() {
100-
return APIAuthenticationType.LOGIN_API;
100+
return APIAuthenticationType.READONLY_API;
101101
}
102102

103103
@Override

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -326,13 +326,13 @@ public String authenticate(final String command, final Map<String, Object[]> par
326326
resp.addCookie(new Cookie("domainid", URLEncoder.encode(loginResponse.getDomainId(), HttpUtils.UTF_8)));
327327
resp.addCookie(new Cookie("role", URLEncoder.encode(loginResponse.getType(), HttpUtils.UTF_8)));
328328
resp.addCookie(new Cookie("username", URLEncoder.encode(loginResponse.getUsername(), HttpUtils.UTF_8)));
329-
resp.addCookie(new Cookie(ApiConstants.SESSIONKEY, URLEncoder.encode(loginResponse.getSessionKey(), HttpUtils.UTF_8)));
330329
resp.addCookie(new Cookie("account", URLEncoder.encode(loginResponse.getAccount(), HttpUtils.UTF_8)));
331330
String timezone = loginResponse.getTimeZone();
332331
if (timezone != null) {
333332
resp.addCookie(new Cookie("timezone", URLEncoder.encode(timezone, HttpUtils.UTF_8)));
334333
}
335334
resp.addCookie(new Cookie("userfullname", URLEncoder.encode(loginResponse.getFirstName() + " " + loginResponse.getLastName(), HttpUtils.UTF_8).replace("+", "%20")));
335+
resp.addHeader("SET-COOKIE", String.format("%s=%s;HttpOnly", ApiConstants.SESSIONKEY, loginResponse.getSessionKey()));
336336
resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
337337
return ApiResponseSerializer.toSerializedString(loginResponse, responseType);
338338
}

‎plugins/user-authenticators/saml2/test/org/apache/cloudstack/GetServiceProviderMetaDataCmdTest.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,6 @@ public void testAuthenticate() throws NoSuchFieldException, SecurityException, I
9797

9898
@Test
9999
public void testGetAPIType() {
100-
Assert.assertTrue(new GetServiceProviderMetaDataCmd().getAPIType() == APIAuthenticationType.LOGIN_API);
100+
Assert.assertTrue(new GetServiceProviderMetaDataCmd().getAPIType() == APIAuthenticationType.READONLY_API);
101101
}
102102
}

‎plugins/user-authenticators/saml2/test/org/apache/cloudstack/api/command/SAML2LoginAPIAuthenticatorCmdTest.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,6 @@ public void testAuthenticate() throws Exception {
196196

197197
@Test
198198
public void testGetAPIType() {
199-
Assert.assertTrue(new GetServiceProviderMetaDataCmd().getAPIType() == APIAuthenticationType.LOGIN_API);
199+
Assert.assertTrue(new SAML2LoginAPIAuthenticatorCmd().getAPIType() == APIAuthenticationType.LOGIN_API);
200200
}
201201
}

‎server/src/com/cloud/api/ApiServlet.java‎

Lines changed: 35 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,13 @@
1616
// under the License.
1717
package com.cloud.api;
1818

19-
import java.io.UnsupportedEncodingException;
20-
import java.net.URLDecoder;
21-
import java.util.HashMap;
22-
import java.util.Map;
23-
24-
import javax.inject.Inject;
25-
import javax.servlet.ServletConfig;
26-
import javax.servlet.ServletException;
27-
import javax.servlet.http.HttpServlet;
28-
import javax.servlet.http.HttpServletRequest;
29-
import javax.servlet.http.HttpServletResponse;
30-
import javax.servlet.http.HttpSession;
31-
19+
import com.cloud.user.Account;
20+
import com.cloud.user.AccountService;
21+
import com.cloud.user.User;
22+
import com.cloud.utils.HttpUtils;
23+
import com.cloud.utils.StringUtils;
24+
import com.cloud.utils.db.EntityManager;
25+
import com.cloud.utils.net.NetUtils;
3226
import org.apache.cloudstack.api.ApiConstants;
3327
import org.apache.cloudstack.api.ApiServerService;
3428
import org.apache.cloudstack.api.ServerApiException;
@@ -41,13 +35,18 @@
4135
import org.springframework.stereotype.Component;
4236
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
4337

44-
import com.cloud.user.Account;
45-
import com.cloud.user.AccountService;
46-
import com.cloud.user.User;
47-
import com.cloud.utils.HttpUtils;
48-
import com.cloud.utils.StringUtils;
49-
import com.cloud.utils.db.EntityManager;
50-
import com.cloud.utils.net.NetUtils;
38+
import javax.inject.Inject;
39+
import javax.servlet.ServletConfig;
40+
import javax.servlet.ServletException;
41+
import javax.servlet.http.Cookie;
42+
import javax.servlet.http.HttpServlet;
43+
import javax.servlet.http.HttpServletRequest;
44+
import javax.servlet.http.HttpServletResponse;
45+
import javax.servlet.http.HttpSession;
46+
import java.io.UnsupportedEncodingException;
47+
import java.net.URLDecoder;
48+
import java.util.HashMap;
49+
import java.util.Map;
5150

5251
@Component("apiServlet")
5352
@SuppressWarnings("serial")
@@ -180,7 +179,7 @@ void processRequestInContext(final HttpServletRequest req, final HttpServletResp
180179
}
181180
session = req.getSession(true);
182181
if (ApiServer.isSecureSessionCookieEnabled()) {
183-
resp.setHeader("SET-COOKIE", "JSESSIONID=" + session.getId() + ";Secure;Path=/client");
182+
resp.setHeader("SET-COOKIE", String.format("JSESSIONID=%s;Secure;HttpOnly;Path=/client", session.getId()));
184183
if (s_logger.isDebugEnabled()) {
185184
if (s_logger.isDebugEnabled()) {
186185
s_logger.debug("Session cookie is marked secure!");
@@ -191,11 +190,15 @@ void processRequestInContext(final HttpServletRequest req, final HttpServletResp
191190

192191
try {
193192
responseString = apiAuthenticator.authenticate(command, params, session, remoteAddress, responseType, auditTrailSb, req, resp);
193+
if (session != null && session.getAttribute(ApiConstants.SESSIONKEY) != null) {
194+
resp.addHeader("SET-COOKIE", String.format("%s=%s;HttpOnly", ApiConstants.SESSIONKEY, session.getAttribute(ApiConstants.SESSIONKEY)));
195+
}
194196
} catch (ServerApiException e) {
195197
httpResponseCode = e.getErrorCode().getHttpCode();
196198
responseString = e.getMessage();
197199
s_logger.debug("Authentication failure: " + e.getMessage());
198200
}
201+
199202
if (apiAuthenticator.getAPIType() == APIAuthenticationType.LOGOUT_API) {
200203
if (session != null) {
201204
final Long userId = (Long) session.getAttribute("userid");
@@ -213,6 +216,9 @@ void processRequestInContext(final HttpServletRequest req, final HttpServletResp
213216
} catch (final IllegalStateException ignored) {
214217
}
215218
}
219+
Cookie sessionKeyCookie = new Cookie(ApiConstants.SESSIONKEY, "");
220+
sessionKeyCookie.setMaxAge(0);
221+
resp.addCookie(sessionKeyCookie);
216222
}
217223
HttpUtils.writeHttpResponse(resp, responseString, httpResponseCode, responseType, ApiServer.getJSONContentType());
218224
return;
@@ -229,11 +235,15 @@ void processRequestInContext(final HttpServletRequest req, final HttpServletResp
229235

230236
if (!isNew) {
231237
userId = (Long)session.getAttribute("userid");
232-
final String account = (String)session.getAttribute("account");
238+
final String account = (String) session.getAttribute("account");
233239
final Object accountObj = session.getAttribute("accountobj");
234-
final String sessionKey = (String)session.getAttribute(ApiConstants.SESSIONKEY);
235-
final String[] sessionKeyParam = (String[])params.get(ApiConstants.SESSIONKEY);
236-
if ((sessionKeyParam == null) || (sessionKey == null) || !sessionKey.equals(sessionKeyParam[0])) {
240+
final String sessionKey = (String) session.getAttribute(ApiConstants.SESSIONKEY);
241+
final String sessionKeyFromCookie = HttpUtils.findCookie(req.getCookies(), ApiConstants.SESSIONKEY);
242+
final String[] sessionKeyFromParams = (String[]) params.get(ApiConstants.SESSIONKEY);
243+
if ((sessionKey == null)
244+
|| (sessionKeyFromParams == null && sessionKeyFromCookie == null)
245+
|| (sessionKeyFromParams != null && !sessionKey.equals(sessionKeyFromParams[0]))
246+
|| (sessionKeyFromCookie != null && !sessionKey.equals(sessionKeyFromCookie))) {
237247
try {
238248
session.invalidate();
239249
} catch (final IllegalStateException ise) {

‎ui/scripts/cloudStack.js‎

Lines changed: 49 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -107,44 +107,27 @@
107107
// Use this for checking the session, to bypass login screen
108108
bypassLoginCheck: function(args) { //determine to show or bypass login screen
109109
if (g_loginResponse == null) { //show login screen
110-
/*
111-
* Since we no longer store sessionKey in cookie, opening the
112-
* 2nd browser window (of the same domain) will show login screen (i.e. user has to
113-
* enter credentials again) and will cause the 1st browser window session timeout.
114-
*/
115110
var unBoxCookieValue = function (cookieName) {
116-
var cookieValue = $.cookie(cookieName);
117-
if (cookieValue && cookieValue.length > 2 && cookieValue[0] === '"' && cookieValue[cookieValue.length-1] === '"') {
118-
cookieValue = cookieValue.slice(1, cookieValue.length-1);
119-
$.cookie(cookieName, cookieValue, { expires: 1 });
120-
}
121-
return decodeURIComponent(cookieValue);
111+
return decodeURIComponent($.cookie(cookieName)).replace(/"([^"]+(?="))"/g, '$1');
122112
};
123-
unBoxCookieValue('sessionkey');
124-
// if sessionkey cookie exists use this to set g_sessionKey
125-
// and destroy sessionkey cookie
126-
if ($.cookie('sessionkey')) {
127-
g_sessionKey = $.cookie('sessionkey');
128-
$.cookie('sessionkey', null);
129-
} else {
130-
g_sessionKey = unBoxCookieValue('JSESSIONID');
131-
}
113+
// sessionkey is a HttpOnly cookie now, no need to pass as API param
114+
g_sessionKey = null;
132115
g_role = unBoxCookieValue('role');
133116
g_userid = unBoxCookieValue('userid');
134117
g_domainid = unBoxCookieValue('domainid');
135118
g_account = unBoxCookieValue('account');
136119
g_username = unBoxCookieValue('username');
137120
g_userfullname = unBoxCookieValue('userfullname');
138121
g_timezone = unBoxCookieValue('timezone');
139-
} else { //single-sign-on (bypass login screen)
122+
} else { //single-sign-on (bypass login screen)
140123
g_sessionKey = encodeURIComponent(g_loginResponse.sessionkey);
141124
g_role = g_loginResponse.type;
142125
g_username = g_loginResponse.username;
143126
g_userid = g_loginResponse.userid;
144127
g_account = g_loginResponse.account;
145128
g_domainid = g_loginResponse.domainid;
146129
g_userfullname = g_loginResponse.firstname + ' ' + g_loginResponse.lastname;
147-
g_timezone = g_loginResponse.timezone;
130+
g_timezone = g_loginResponse.timezone;
148131
}
149132

150133
var userValid = false;
@@ -180,7 +163,25 @@
180163
return true;
181164
}
182165
});
183-
166+
167+
// Populate IDP list
168+
$.ajax({
169+
type: 'GET',
170+
url: createURL('listIdps'),
171+
dataType: 'json',
172+
async: false,
173+
success: function(data, textStatus, xhr) {
174+
if (data && data.listidpsresponse && data.listidpsresponse.idp) {
175+
var idpList = data.listidpsresponse.idp.sort(function (a, b) {
176+
return a.orgName.localeCompare(b.orgName);
177+
});
178+
g_idpList = idpList;
179+
}
180+
},
181+
error: function(xhr) {
182+
},
183+
});
184+
184185
return userValid ? {
185186
user: {
186187
userid: g_userid,
@@ -227,14 +228,16 @@
227228
async: false,
228229
success: function(json) {
229230
var loginresponse = json.loginresponse;
230-
231-
g_sessionKey = encodeURIComponent(loginresponse.sessionkey);
231+
// sessionkey is recevied as a HttpOnly cookie
232+
// therefore reset any g_sessionKey value, an explicit
233+
// param in the API call is no longer needed
234+
g_sessionKey = null;
232235
g_role = loginresponse.type;
233236
g_username = loginresponse.username;
234237
g_userid = loginresponse.userid;
235238
g_account = loginresponse.account;
236239
g_domainid = loginresponse.domainid;
237-
g_timezone = loginresponse.timezone;
240+
g_timezone = loginresponse.timezone;
238241
g_userfullname = loginresponse.firstname + ' ' + loginresponse.lastname;
239242

240243
$.cookie('username', g_username, {
@@ -320,7 +323,7 @@
320323
$.ajax({
321324
url: createURL('logout'),
322325
async: false,
323-
success: function() {
326+
success: function() {
324327
g_sessionKey = null;
325328
g_username = null;
326329
g_account = null;
@@ -331,15 +334,16 @@
331334
g_kvmsnapshotenabled = null;
332335
g_regionsecondaryenabled = null;
333336
g_loginCmdText = null;
334-
335-
$.cookie('JSESSIONID', null);
336-
$.cookie('sessionkey', null);
337-
$.cookie('username', null);
338-
$.cookie('account', null);
339-
$.cookie('domainid', null);
340-
$.cookie('role', null);
341-
$.cookie('timezone', null);
342-
337+
338+
// Remove any cookies
339+
var cookies = document.cookie.split(";");
340+
for (var i = 0; i < cookies.length; i++) {
341+
var cookieName = $.trim(cookies[i].split("=")[0]);
342+
if (['login-option', 'lang'].indexOf(cookieName) < 0) {
343+
$.cookie(cookieName, null);
344+
}
345+
}
346+
343347
if (onLogoutCallback()) { //onLogoutCallback() will set g_loginResponse(single-sign-on variable) to null, then bypassLoginCheck() will show login screen.
344348
document.location.reload(); //when onLogoutCallback() returns true, reload the current document.
345349
}
@@ -367,13 +371,15 @@
367371
g_regionsecondaryenabled = null;
368372
g_loginCmdText = null;
369373

370-
$.cookie('JSESSIONID', null);
371-
$.cookie('sessionkey', null);
372-
$.cookie('username', null);
373-
$.cookie('account', null);
374-
$.cookie('domainid', null);
375-
$.cookie('role', null);
376-
$.cookie('timezone', null);
374+
// Remove any cookies
375+
var cookies = document.cookie.split(";");
376+
for (var i = 0; i < cookies.length; i++) {
377+
var cookieName = $.trim(cookies[i].split("=")[0]);
378+
if (['login-option', 'lang'].indexOf(cookieName) < 0) {
379+
$.cookie(cookieName, null);
380+
}
381+
}
382+
377383
var url = 'samlSso';
378384
if (args.data.idpid) {
379385
url = url + '&idpid=' + args.data.idpid;

‎ui/scripts/sharedFunctions.js‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,10 @@ var pollAsyncJobResult = function(args) {
170170

171171
function createURL(apiName, options) {
172172
if (!options) options = {};
173-
var urlString = clientApiUrl + "?" + "command=" + apiName + "&response=json&sessionkey=" + g_sessionKey;
173+
var urlString = clientApiUrl + "?" + "command=" + apiName + "&response=json";
174+
if (g_sessionKey) {
175+
urlString += "&sessionkey=" + g_sessionKey;
176+
}
174177

175178
if (cloudStack.context && cloudStack.context.projects && !options.ignoreProject) {
176179
urlString = urlString + '&projectid=' + cloudStack.context.projects[0].id;

0 commit comments

Comments
 (0)