Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix missing claims for federated users for jwt token issuers #2613

Merged
merged 10 commits into from
Dec 18, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

package org.wso2.carbon.identity.oauth.cache;

import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTParser;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
Expand All @@ -29,10 +31,10 @@
import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.dao.OAuthTokenPersistenceFactory;
import org.wso2.carbon.identity.oauth2.model.AccessTokenDO;
import org.wso2.carbon.identity.oauth2.util.OAuth2Util;
import org.wso2.carbon.utils.CarbonUtils;

import java.text.ParseException;
import java.util.concurrent.TimeUnit;

/**
Expand Down Expand Up @@ -237,11 +239,19 @@ private String replaceFromCodeId(String authzCode) {
* @return TOKEN_ID from the database
*/
private String replaceFromTokenId(String keyValue) {
try {
AccessTokenDO accessTokenDO = OAuth2Util.findAccessToken(keyValue, true);
if (accessTokenDO != null) {
return accessTokenDO.getTokenId();
if (OAuth2Util.isJWT(keyValue)) {
try {
JWT parsedJwtToken = JWTParser.parse(keyValue);
keyValue = parsedJwtToken.getJWTClaimsSet().getJWTID();
} catch (ParseException e) {
if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(
IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
log.debug("Error while getting JWTID from token: " + keyValue, e);
sandushi marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
try {
return OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getTokenIdByAccessToken(keyValue);
} catch (IdentityOAuth2Exception e) {
log.error("Failed to retrieve token id by token from store for - ." + keyValue, e);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
package org.wso2.carbon.identity.oauth.cache;
sandushi marked this conversation as resolved.
Show resolved Hide resolved

import com.nimbusds.jwt.JWT;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.JWTParser;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.wso2.carbon.identity.application.authentication.framework.store.SessionDataStore;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;
import org.wso2.carbon.identity.oauth2.dao.AccessTokenDAO;
import org.wso2.carbon.identity.oauth2.dao.AuthorizationCodeDAO;
import org.wso2.carbon.identity.oauth2.dao.OAuthTokenPersistenceFactory;

import java.text.ParseException;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class AuthorizationGrantCacheTest {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shall we add class comment

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed with e607ea0


@Mock
private AccessTokenDAO accessTokenDAO;

private AuthorizationGrantCache cache;

@Mock
private OAuthTokenPersistenceFactory mockedOAuthTokenPersistenceFactory;

@Mock
private AuthorizationCodeDAO authorizationCodeDAO;

@Mock
private SessionDataStore sessionDataStore;

private static final String AUTHORIZATION_GRANT_CACHE_NAME = "AuthorizationGrantCache";

@BeforeMethod
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
cache = AuthorizationGrantCache.getInstance();
}

@Test(dataProvider = "replaceFromTokenIdDataProvider")
public void testReplaceFromTokenId(String accessToken, String jwtId, String tokenId, boolean isJwtToken,
boolean isInvalidJWTToken, boolean isFailedTokenRetrieval) throws Exception {

try (MockedStatic<OAuthTokenPersistenceFactory> mockedFactory = mockStatic(OAuthTokenPersistenceFactory.class);
MockedStatic<JWTParser> mockedJwtParser = mockStatic(JWTParser.class);
MockedStatic<SessionDataStore> mockedSessionDataStore = mockStatic(SessionDataStore.class);
MockedStatic<IdentityUtil> mockedIdentityUtil = mockStatic(IdentityUtil.class)) {

mockedFactory.when(OAuthTokenPersistenceFactory::getInstance).thenReturn(
mockedOAuthTokenPersistenceFactory);

when(mockedOAuthTokenPersistenceFactory.getAccessTokenDAO()).thenReturn(accessTokenDAO);

if (isJwtToken) {
JWT jwtMock = mock(JWT.class);
JWTClaimsSet claimsSetMock = mock(JWTClaimsSet.class);

if (isInvalidJWTToken) {
when(JWTParser.parse(accessToken)).thenThrow(new ParseException("Invalid JWT", 0));
} else {
mockedJwtParser.when(() -> JWTParser.parse(accessToken)).thenReturn(jwtMock);
when(jwtMock.getJWTClaimsSet()).thenReturn(claimsSetMock);
when(claimsSetMock.getJWTID()).thenReturn(jwtId);
}
}

if (isFailedTokenRetrieval) {
when(accessTokenDAO.getTokenIdByAccessToken(jwtId)).thenThrow(
new IdentityOAuth2Exception("Failed to retrieve token id by token from store"));
} else {
when(accessTokenDAO.getTokenIdByAccessToken(jwtId != null ? jwtId : accessToken)).thenReturn(tokenId);
}

// Mock SessionDataStore static instance and return a mock session data store
sandushi marked this conversation as resolved.
Show resolved Hide resolved
mockedSessionDataStore.when(SessionDataStore::getInstance).thenReturn(sessionDataStore);

// Mock SessionDataStore return for session data (from getFromSessionStore)
sandushi marked this conversation as resolved.
Show resolved Hide resolved
AuthorizationGrantCacheEntry mockCacheEntry = new AuthorizationGrantCacheEntry();
mockCacheEntry.setTokenId(tokenId);

when(sessionDataStore.getSessionData(tokenId, AUTHORIZATION_GRANT_CACHE_NAME)).thenReturn(mockCacheEntry);

AuthorizationGrantCacheKey key = new AuthorizationGrantCacheKey(accessToken);
AuthorizationGrantCacheEntry result = cache.getValueFromCacheByToken(key);

// Verify the token ID returned from the DAO is as expected
sandushi marked this conversation as resolved.
Show resolved Hide resolved
assertEquals(tokenId, result.getTokenId());

// Verify that the JWT token was parsed and the correct claim was retrieved if it was a JWT
if (isJwtToken && !isInvalidJWTToken) {
verify(accessTokenDAO).getTokenIdByAccessToken(jwtId);
} else {
verify(accessTokenDAO).getTokenIdByAccessToken(accessToken);
}
}
}

@DataProvider(name = "replaceFromTokenIdDataProvider")
public Object[][] getReplaceFromTokenIdData() {
return new Object[][]{
{"jwt.Access.Token", "jwtId", "jwtTokenId", true, false, false},
sandushi marked this conversation as resolved.
Show resolved Hide resolved
{"nonJWTAccessToken", null, "nonJWTTokenId", false, false, false},
{"invalid.JWT.Token", null, "invalid.JWT.Token", true, true, false},
{"fail.Store.TokenId", "jwtId", "jwtId", true, false, true}
};
}

@Test
public void testGetValueFromCacheByCode() throws IdentityOAuth2Exception {
String authCode = "authCode";
String codeId = "codeId";
sandushi marked this conversation as resolved.
Show resolved Hide resolved
AuthorizationGrantCacheKey key = new AuthorizationGrantCacheKey(authCode);
AuthorizationGrantCacheEntry expectedEntry = new AuthorizationGrantCacheEntry();
expectedEntry.setCodeId(codeId);

try (MockedStatic<OAuthTokenPersistenceFactory> mockedFactory = mockStatic(OAuthTokenPersistenceFactory.class);
MockedStatic<SessionDataStore> mockedSessionDataStore = mockStatic(SessionDataStore.class);
MockedStatic<IdentityUtil> mockedIdentityUtil = mockStatic(IdentityUtil.class)) {

mockedSessionDataStore.when(SessionDataStore::getInstance).thenReturn(sessionDataStore);
when(sessionDataStore.getSessionData(codeId, "AuthorizationGrantCache")).thenReturn(expectedEntry);

mockedFactory.when(OAuthTokenPersistenceFactory::getInstance).
thenReturn(mockedOAuthTokenPersistenceFactory);
when(mockedOAuthTokenPersistenceFactory.getAuthorizationCodeDAO()).thenReturn(authorizationCodeDAO);
when(authorizationCodeDAO.getCodeIdByAuthorizationCode(authCode)).thenReturn(codeId);

AuthorizationGrantCacheEntry result = cache.getValueFromCacheByCode(key);

assertEquals(expectedEntry, result);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@
<class name="org.wso2.carbon.identity.oauth2.device.codegenerator.GenerateKeysTest"/>
<class name="org.wso2.carbon.identity.oauth2.responsemode.provider.ResponseModeProviderTest"/>
<class name="org.wso2.carbon.identity.oauth2.token.handlers.claims.ImpersonatedAccessTokenClaimProviderTest"/>
<class name="org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheTest"/>
</classes>
</test>

Expand Down Expand Up @@ -198,6 +199,7 @@
<class name="org.wso2.carbon.identity.openidconnect.OpenIDConnectSystemClaimImplTest"/>
<class name="org.wso2.carbon.identity.openidconnect.OpenIDConnectClaimFilterImplTest"/>
<class name="org.wso2.carbon.identity.openidconnect.util.ClaimHandlerUtilTest"/>
<class name="org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheTest"/>
</classes>
</test>
</suite>
Loading