Skip to content

Commit

Permalink
Reduce duplicate code
Browse files Browse the repository at this point in the history
  • Loading branch information
fyrbach committed Jun 7, 2024
1 parent 0990980 commit 1eb243a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 133 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
* information: "Portions copyright [year] [name of copyright owner]".
*
* Copyright 2013-2016 ForgeRock AS.
* Portions copyright 2024 Wren Security.
*/

package org.forgerock.openam.core.rest.session;
Expand All @@ -32,12 +33,14 @@
import static org.forgerock.openam.utils.Time.currentTimeMillis;
import static org.forgerock.util.promise.Promises.newResultPromise;

import com.iplanet.dpro.session.share.SessionInfo;
import com.iplanet.services.naming.WebtopNaming;
import com.iplanet.sso.SSOTokenManager;
import com.sun.identity.common.CaseInsensitiveHashMap;
import com.sun.identity.shared.debug.Debug;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.forgerock.api.annotations.Action;
import org.forgerock.api.annotations.Actions;
import org.forgerock.api.annotations.ApiError;
Expand All @@ -49,7 +52,6 @@
import org.forgerock.api.annotations.Query;
import org.forgerock.api.annotations.Schema;
import org.forgerock.api.enums.QueryType;
import org.forgerock.http.header.CookieHeader;
import org.forgerock.json.JsonValue;
import org.forgerock.json.resource.ActionRequest;
import org.forgerock.json.resource.ActionResponse;
Expand Down Expand Up @@ -86,14 +88,6 @@
import org.forgerock.services.context.Context;
import org.forgerock.util.promise.Promise;

import com.iplanet.am.util.SystemProperties;
import com.iplanet.dpro.session.share.SessionInfo;
import com.iplanet.services.naming.WebtopNaming;
import com.iplanet.sso.SSOTokenManager;
import com.sun.identity.common.CaseInsensitiveHashMap;
import com.sun.identity.shared.Constants;
import com.sun.identity.shared.debug.Debug;

/**
* Represents Sessions that can queried via a REST interface.
*
Expand Down Expand Up @@ -416,20 +410,8 @@ public Collection<String> getAllServerIds() {
)
})
public Promise<ActionResponse, ResourceException> actionCollection(Context context, ActionRequest request) {
final String cookieName = SystemProperties.get(Constants.AM_COOKIE_NAME, "iPlanetDirectoryPro");

String tokenId = getTokenIdFromUrlParam(request);
String tokenId = SessionResourceUtil.getTokenId(context.asContext(HttpContext.class), request);

if (tokenId == null) {
tokenId = getTokenIdFromHeader(context, cookieName);
}

if (tokenId == null) {
tokenId = getTokenIdFromCookie(context, cookieName);
}

// Should any of these actions in the future be allowed to function without an SSO token, this
// code will have to be moved/changed.
if (tokenId == null) {
final BadRequestException e = new BadRequestException("iPlanetDirectoryCookie not set on request");
LOGGER.message("SessionResource.handleNullSSOToken :: iPlanetDirectoryCookie not set on request", e);
Expand All @@ -439,31 +421,6 @@ public Promise<ActionResponse, ResourceException> actionCollection(Context conte
return internalHandleAction(tokenId, context, request);
}

protected String getTokenIdFromUrlParam(ActionRequest request) {
return request.getAdditionalParameter("tokenId");
}

protected String getTokenIdFromCookie(Context context, String cookieName) {
final List<String> header = context.asContext(HttpContext.class).getHeader(cookieName.toLowerCase());
if (!header.isEmpty()) {
return header.get(0);
}
return null;
}

protected String getTokenIdFromHeader(Context context, String cookieName) {
final List<String> headers = context.asContext(HttpContext.class).getHeader("cookie");

for (String header : headers) {
for (org.forgerock.http.protocol.Cookie cookie : CookieHeader.valueOf(header).getCookies()) {
if (cookie.getName().equalsIgnoreCase(cookieName)) {
return cookie.getValue();
}
}
}
return null;
}

/**
* Actions supported are:
* <ul>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
* information: "Portions copyright [year] [name of copyright owner]".
*
* Copyright 2016 ForgeRock AS.
* Portions copyright 2024 Wren Security.
*/
package org.forgerock.openam.core.rest.session;

Expand All @@ -24,15 +25,12 @@

import javax.inject.Inject;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.iplanet.am.util.SystemProperties;
import com.iplanet.dpro.session.SessionException;
import com.iplanet.dpro.session.service.SessionService;
import com.iplanet.sso.SSOTokenManager;
import com.sun.identity.common.CaseInsensitiveHashMap;
import com.sun.identity.shared.Constants;
import com.sun.identity.shared.debug.Debug;
import org.forgerock.api.annotations.Action;
import org.forgerock.api.annotations.Actions;
Expand All @@ -45,7 +43,6 @@
import org.forgerock.api.annotations.Schema;
import org.forgerock.api.enums.ParameterSource;
import org.forgerock.api.enums.QueryType;
import org.forgerock.http.header.CookieHeader;
import org.forgerock.json.resource.ActionRequest;
import org.forgerock.json.resource.ActionResponse;
import org.forgerock.json.resource.BadRequestException;
Expand Down Expand Up @@ -120,10 +117,7 @@ public class SessionResourceV2 implements CollectionResourceProvider {
public static final String UPDATE_SESSION_PROPERTIES_ACTION_ID = "updateSessionProperties";
public static final String LOGOUT_BY_HANDLE_ACTION_ID = "logoutByHandle";

private final SessionPropertyWhitelist sessionPropertyWhitelist;

private final Map<String, ActionHandler> actionHandlers;
private final SessionResourceUtil sessionResourceUtil;
private final SessionService sessionService;

/**
Expand All @@ -138,8 +132,6 @@ public class SessionResourceV2 implements CollectionResourceProvider {
public SessionResourceV2(final SSOTokenManager ssoTokenManager, AuthUtilsWrapper authUtilsWrapper,
final SessionResourceUtil sessionResourceUtil, SessionPropertyWhitelist sessionPropertyWhitelist,
SessionService sessionService, PartialSessionFactory partialSessionFactory) {
this.sessionResourceUtil = sessionResourceUtil;
this.sessionPropertyWhitelist = sessionPropertyWhitelist;
this.sessionService = sessionService;
actionHandlers = new CaseInsensitiveHashMap<>();
actionHandlers.put(REFRESH_ACTION_ID,
Expand Down Expand Up @@ -265,19 +257,8 @@ public SessionResourceV2(final SSOTokenManager ssoTokenManager, AuthUtilsWrapper
})
@Override
public Promise<ActionResponse, ResourceException> actionCollection(Context context, ActionRequest request) {
final String cookieName = SystemProperties.get(Constants.AM_COOKIE_NAME, "iPlanetDirectoryPro");
String tokenId = getTokenIdFromUrlParam(request);
String tokenId = SessionResourceUtil.getTokenId(context.asContext(HttpContext.class), request);

if (tokenId == null) {
tokenId = getTokenIdFromHeader(context, cookieName);
}

if (tokenId == null) {
tokenId = getTokenIdFromCookie(context, cookieName);
}

// Should any of these actions in the future be allowed to function without an SSO token, this
// code will have to be moved/changed.
if (tokenId == null) {
final BadRequestException e = new BadRequestException("iPlanetDirectoryCookie not set on request");
LOGGER.message("SessionResource.handleNullSSOToken :: iPlanetDirectoryCookie not set on request", e);
Expand All @@ -287,31 +268,6 @@ public Promise<ActionResponse, ResourceException> actionCollection(Context conte
return internalHandleAction(tokenId, context, request);
}

protected String getTokenIdFromUrlParam(ActionRequest request) {
return request.getAdditionalParameter("tokenId");
}

protected String getTokenIdFromCookie(Context context, String cookieName) {
final List<String> header = context.asContext(HttpContext.class).getHeader(cookieName.toLowerCase());
if (!header.isEmpty()) {
return header.get(0);
}
return null;
}

protected String getTokenIdFromHeader(Context context, String cookieName) {
final List<String> headers = context.asContext(HttpContext.class).getHeader("cookie");

for (String header : headers) {
for (org.forgerock.http.protocol.Cookie cookie : CookieHeader.valueOf(header).getCookies()) {
if (cookie.getName().equalsIgnoreCase(cookieName)) {
return cookie.getValue();
}
}
}
return null;
}

/**
* Handle the action specified by the user (i.e. one of those in the validActions set).
* @param tokenId The id of the token.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
* information: "Portions copyright [year] [name of copyright owner]".
*
* Copyright 2013-2015 ForgeRock AS.
* Portions Copyright 2021 Wren Security.
* Portions Copyright 2021-2024 Wren Security.
*/

package org.forgerock.openam.core.rest.session;
Expand Down Expand Up @@ -70,6 +70,7 @@
import org.forgerock.json.resource.QueryRequest;
import org.forgerock.json.resource.QueryResourceHandler;
import org.forgerock.json.resource.ResourceException;
import org.forgerock.json.resource.http.HttpContext;
import org.forgerock.openam.authentication.service.AuthUtilsWrapper;
import org.forgerock.openam.core.realms.Realm;
import org.forgerock.openam.core.realms.RealmTestHelper;
Expand All @@ -82,7 +83,6 @@
import org.forgerock.services.context.AttributesContext;
import org.forgerock.services.context.ClientContext;
import org.forgerock.services.context.Context;
import org.forgerock.services.context.RootContext;
import org.forgerock.services.context.SecurityContext;
import org.forgerock.util.promise.Promise;
import org.testng.annotations.AfterMethod;
Expand Down Expand Up @@ -115,22 +115,13 @@ public class SessionResourceTest {

private AMIdentity amIdentity;

private String headerResponse;
private String urlResponse;
private String cookieResponse;



@BeforeMethod
public void setUp() throws Exception {
SessionQueryManager sessionQueryManager = mock(SessionQueryManager.class);
ssoTokenManager = mock(SSOTokenManager.class);
authUtilsWrapper = mock(AuthUtilsWrapper.class);
propertyWhitelist = mock(SessionPropertyWhitelist.class);
webtopNamingQuery = mock(WebtopNamingQuery.class);
headerResponse = null;
urlResponse = null;
cookieResponse = null;

given(mockContext.getCallerSSOToken()).willReturn(ssoToken);

Expand Down Expand Up @@ -164,25 +155,7 @@ public String convertDNToRealm(String dn) {
}
});

sessionResource = new SessionResource(ssoTokenManager, authUtilsWrapper,
propertyWhitelist, sessionResourceUtil) {

@Override
protected String getTokenIdFromHeader(Context context, String cookieName) {
return headerResponse;
}

@Override
protected String getTokenIdFromUrlParam(ActionRequest request) {
return urlResponse;
}

@Override
protected String getTokenIdFromCookie(Context context, String cookieName) {
return cookieResponse;
}

};
sessionResource = new SessionResource(ssoTokenManager, authUtilsWrapper, propertyWhitelist, sessionResourceUtil);
}

@AfterMethod
Expand Down Expand Up @@ -251,10 +224,11 @@ public void shouldQueryNamedServerInServerMode() {
@Test
public void actionCollectionShouldFailToValidateSessionWhenSSOTokenIdNotSet() {
//Given
final SSOTokenContext tokenContext = mock(SSOTokenContext.class);
final Context context = ClientContext.newInternalClientContext(tokenContext);
final HttpContext httpContext = mock(HttpContext.class);
final Context context = mock(ClientContext.class);
final ActionRequest request = mock(ActionRequest.class);

given(context.asContext(HttpContext.class)).willReturn(httpContext);
given(request.getAction()).willReturn(VALIDATE_ACTION_ID);

//When
Expand All @@ -267,13 +241,15 @@ public void actionCollectionShouldFailToValidateSessionWhenSSOTokenIdNotSet() {
@Test
public void actionCollectionShouldValidateSessionAndReturnTrueWhenSSOTokenValid() throws SSOException {
//Given
cookieResponse = "SSO_TOKEN_ID";
final SSOTokenContext tokenContext = mock(SSOTokenContext.class);
final Context context = ClientContext.newInternalClientContext(tokenContext);
final HttpContext httpContext = mock(HttpContext.class);
final Context context = mock(ClientContext.class);
final ActionRequest request = mock(ActionRequest.class);
final SSOToken ssoToken = mock(SSOToken.class);
final SSOTokenID ssoTokenId = mock(SSOTokenID.class);

given(context.asContext(HttpContext.class)).willReturn(httpContext);
given(httpContext.getHeader("cookie")).willReturn(List.of("iPlanetDirectoryPro=SSO_TOKEN_ID"));
given(request.getAction()).willReturn(VALIDATE_ACTION_ID);
given(tokenContext.getCallerSSOToken()).willReturn(ssoToken);
given(ssoTokenManager.isValidToken(ssoToken)).willReturn(true);
Expand All @@ -294,14 +270,15 @@ public void actionCollectionShouldValidateSessionAndReturnTrueWhenSSOTokenValid(
@Test
public void actionCollectionShouldLogoutSessionAndReturnEmptyJsonObjectWhenSSOTokenValid() throws SSOException {
//Given
cookieResponse = "SSO_TOKEN_ID";
final AttributesContext attrContext = new AttributesContext(new SessionContext(new RootContext(), mock(Session.class)));
final AdviceContext adviceContext = new AdviceContext(attrContext, Collections.<String>emptySet());
final HttpContext httpContext = mock(HttpContext.class);
final AttributesContext attrContext = new AttributesContext(new SessionContext(httpContext, mock(Session.class)));
final AdviceContext adviceContext = new AdviceContext(attrContext, Collections.emptySet());
final SecurityContext securityContext = new SecurityContext(adviceContext, null, null);
final Context context = ClientContext.newInternalClientContext(new SSOTokenContext(mock(Debug.class), null, securityContext));
final ActionRequest request = mock(ActionRequest.class);
final SSOTokenID ssoTokenId = mock(SSOTokenID.class);

given(request.getAdditionalParameter("tokenId")).willReturn("SSO_TOKEN_ID");
given(request.getAction()).willReturn(LOGOUT_ACTION_ID);
given(authUtilsWrapper.logout(ssoTokenId.toString(), null, null)).willReturn(true);

Expand Down

0 comments on commit 1eb243a

Please sign in to comment.