Refactor legacy test suite's TimeOffset (#48756)

* Create fake timeoffset object

Signed-off-by: Simon Vacek <simonvacky@email.cz>

* Remove AbstractKeycloakTest#invokeTimeOffset

Signed-off-by: Simon Vacek <simonvacky@email.cz>

* Remove TestinResource#setTimeOffset & #getTimeOffSet

Signed-off-by: Simon Vacek <simonvacky@email.cz>

* Remove AbstractKeycloakTest#setTimeOffset & getTimeOffset

Signed-off-by: Simon Vacek <simonvacky@email.cz>

---------

Signed-off-by: Simon Vacek <simonvacky@email.cz>
This commit is contained in:
Šimon Vacek
2026-05-13 06:53:32 +02:00
committed by GitHub
parent a676b7576a
commit e52ea63766
71 changed files with 337 additions and 365 deletions
@@ -52,7 +52,6 @@ import org.keycloak.common.Profile.Feature;
import org.keycloak.common.enums.HostnameVerificationPolicy;
import org.keycloak.common.profile.PropertiesProfileConfigResolver;
import org.keycloak.common.util.HtmlUtils;
import org.keycloak.common.util.Time;
import org.keycloak.component.ComponentModel;
import org.keycloak.events.Event;
import org.keycloak.events.EventListenerProvider;
@@ -72,7 +71,6 @@ import org.keycloak.models.UserProvider;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.session.UserSessionPersisterProvider;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.models.utils.ResetTimeOffsetEvent;
import org.keycloak.protocol.oid4vc.issuance.OID4VCIssuerWellKnownProvider;
import org.keycloak.protocol.oid4vc.issuance.credentialoffer.CredentialOfferState;
import org.keycloak.protocol.oid4vc.issuance.credentialoffer.CredentialOfferStorage;
@@ -187,33 +185,6 @@ public class TestingResourceProvider implements RealmResourceProvider {
return sessionModel.getAuthenticatedClientSessions().size();
}
@GET
@Path("/time-offset")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> getTimeOffset() {
Map<String, String> response = new HashMap<>();
response.put("currentTime", String.valueOf(Time.currentTime()));
response.put("offset", String.valueOf(Time.getOffset()));
return response;
}
@PUT
@Path("/time-offset")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> setTimeOffset(Map<String, String> time) {
int offset = Integer.parseInt(time.get("offset"));
Time.setOffset(offset);
// Time offset was restarted
if (offset == 0) {
session.getKeycloakSessionFactory().publish(new ResetTimeOffsetEvent());
}
return getTimeOffset();
}
@POST
@Path("/poll-event-queue")
@Produces(MediaType.APPLICATION_JSON)
@@ -54,17 +54,6 @@ import org.jboss.resteasy.reactive.NoCache;
@Consumes(MediaType.APPLICATION_JSON)
public interface TestingResource {
@GET
@Path("/time-offset")
@Produces(MediaType.APPLICATION_JSON)
Map<String, String> getTimeOffset();
@PUT
@Path("/time-offset")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Map<String, String> setTimeOffset(Map<String, String> time);
@POST
@Path("/poll-event-queue")
@Produces(MediaType.APPLICATION_JSON)
@@ -0,0 +1,35 @@
package org.keycloak.testframework.remote.timeoffset;
import org.keycloak.common.util.Time;
import org.keycloak.models.utils.ResetTimeOffsetEvent;
import org.keycloak.testsuite.AbstractKeycloakTest;
public class TimeOffSet {
private final AbstractKeycloakTest test;
public TimeOffSet(AbstractKeycloakTest test) {
this.test = test;
}
public void set(int offset) {
test.shouldResetTimeOffset(offset != 0);
// adminClient depends on Time.offset for auto-refreshing tokens
Time.setOffset(offset);
test.getTestingClient().server().run(
session -> {
Time.setOffset(offset);
// Time offset was restarted
if (offset == 0) {
session.getKeycloakSessionFactory().publish(new ResetTimeOffsetEvent());
}
}
);
// force getting new token after time offset has changed
test.getAdminClient().tokenManager().grantToken();
}
}
@@ -58,6 +58,7 @@ import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.RequiredActionProviderRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.testframework.remote.timeoffset.TimeOffSet;
import org.keycloak.testsuite.admin.AdminApiUtil;
import org.keycloak.testsuite.arquillian.KcArquillian;
import org.keycloak.testsuite.arquillian.SuiteContext;
@@ -139,6 +140,8 @@ public abstract class AbstractKeycloakTest {
protected KeycloakTestingClient.Server runOnServer;
protected TimeOffSet timeOffSet = new TimeOffSet(this);
@ArquillianResource
protected OAuthClient oauth;
@@ -237,7 +240,7 @@ public abstract class AbstractKeycloakTest {
@After
public void afterAbstractKeycloakTest() throws Exception {
if (resetTimeOffset) {
resetTimeOffset();
timeOffSet.set(0);
}
if (isImportAfterEachMethod()) {
@@ -674,29 +677,15 @@ public abstract class AbstractKeycloakTest {
now.set(Calendar.SECOND, second);
int offset = (int) ((now.getTime().getTime() - System.currentTimeMillis()) / 1000);
setTimeOffset(offset + addSeconds);
timeOffSet.set(offset + addSeconds);
}
/**
* Sets time offset in seconds that will be added to Time.currentTime() and Time.currentTimeMillis() both for client and server.
* Moves time on the remote Infinispan server as well if the HotRod storage is used.
*
* @param offset
*/
public void setTimeOffset(int offset) {
String response = invokeTimeOffset(offset);
resetTimeOffset = offset != 0;
log.debugv("Set time offset, response {0}", response);
}
public void resetTimeOffset() {
String response = invokeTimeOffset(0);
resetTimeOffset = false;
log.debugv("Reset time offset, response {0}", response);
public void shouldResetTimeOffset(boolean resetTimeOffset) {
this.resetTimeOffset = resetTimeOffset;
}
public void setOtpTimeOffset(int offsetSeconds, TimeBasedOTP otp) {
setTimeOffset(offsetSeconds);
timeOffSet.set(offsetSeconds);
final Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, offsetSeconds);
otp.setCalendar(calendar);
@@ -706,18 +695,6 @@ public abstract class AbstractKeycloakTest {
return Time.currentTime();
}
protected String invokeTimeOffset(int offset) {
// adminClient depends on Time.offset for auto-refreshing tokens
Time.setOffset(offset);
Map result = testingClient.testing().setTimeOffset(Collections.singletonMap("offset", String.valueOf(offset)));
// force getting new token after time offset has changed
adminClient.tokenManager().grantToken();
return String.valueOf(result);
}
private void loadConstantsProperties() throws ConfigurationException {
constantsProperties = new PropertiesConfiguration(System.getProperty("testsuite.constants"));
constantsProperties.setThrowExceptionOnMissing(true);
@@ -199,7 +199,7 @@ public class AppInitiatedActionResetPasswordTest extends AbstractAppInitiatedAct
EventAssertion.expectLoginSuccess(events.poll());
setTimeOffset(350);
timeOffSet.set(350);
// Should prompt for re-authentication
doAIA();
@@ -236,7 +236,7 @@ public class AppInitiatedActionResetPasswordTest extends AbstractAppInitiatedAct
EventAssertion.expectLoginSuccess(events.poll());
setTimeOffset(550);
timeOffSet.set(550);
// Should prompt for re-authentication
doAIA();
@@ -275,7 +275,7 @@ public class AppInitiatedActionResetPasswordTest extends AbstractAppInitiatedAct
EventAssertion.expectLoginSuccess(events.poll());
setTimeOffset(350);
timeOffSet.set(350);
// Should not prompt for re-authentication
doAIA();
@@ -313,7 +313,7 @@ public class AppInitiatedActionResetPasswordTest extends AbstractAppInitiatedAct
EventAssertion.expectLoginSuccess(events.poll());
// we need to add some slack to avoid timing issues
setTimeOffset(1);
timeOffSet.set(1);
// Should prompt for re-authentication due to maxAuthAge password policy
doAIA();
@@ -57,7 +57,7 @@ public class AppInitiatedActionUpdateEmailTest extends AbstractAppInitiatedActio
@After
public void after() {
setTimeOffset(0);
timeOffSet.set(0);
// update email required action max auth age back to default
Optional<RequiredActionProviderRepresentation> updateEmailAction = managedRealm.admin().flows().getRequiredActions()
.stream()
@@ -145,7 +145,7 @@ public class AppInitiatedActionUpdateEmailTest extends AbstractAppInitiatedActio
appPage.openAccount();
loginPage.login("test-user@localhost", "password");
setTimeOffset(400);
timeOffSet.set(400);
UIUtils.clickLink(updateEmailBtn);
loginPage.assertCurrent();
loginPage.login("password");
@@ -456,11 +456,11 @@ public class RequiredActionEmailVerificationTest extends AbstractTestRealmKeyclo
Assertions.assertEquals(1, mail.getReceivedMessages().length);
try {
setTimeOffset(40);
timeOffSet.set(40);
verifyEmailPage.clickResendEmail();
Assertions.assertEquals(2, mail.getReceivedMessages().length);
} finally {
setTimeOffset(0);
timeOffSet.set(0);
}
}
@@ -681,7 +681,7 @@ public class RequiredActionEmailVerificationTest extends AbstractTestRealmKeyclo
events.poll();
try {
setTimeOffset(360);
timeOffSet.set(360);
driver.navigate().to(verificationUrl.trim());
@@ -697,7 +697,7 @@ public class RequiredActionEmailVerificationTest extends AbstractTestRealmKeyclo
.detail(Details.ACTION, VerifyEmailActionToken.TOKEN_TYPE)
.assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
}
}
@@ -723,7 +723,7 @@ public class RequiredActionEmailVerificationTest extends AbstractTestRealmKeyclo
events.poll();
try {
setTimeOffset(70);
timeOffSet.set(70);
driver.navigate().to(verificationUrl.trim());
@@ -739,7 +739,7 @@ public class RequiredActionEmailVerificationTest extends AbstractTestRealmKeyclo
.detail(Details.ACTION, VerifyEmailActionToken.TOKEN_TYPE)
.assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
realmRep.setAttributes(originalAttributes);
managedRealm.admin().update(realmRep);
}
@@ -768,7 +768,7 @@ public class RequiredActionEmailVerificationTest extends AbstractTestRealmKeyclo
events.poll();
try {
setTimeOffset(70);
timeOffSet.set(70);
driver.navigate().to(verificationUrl.trim());
@@ -784,7 +784,7 @@ public class RequiredActionEmailVerificationTest extends AbstractTestRealmKeyclo
.detail(Details.ACTION, VerifyEmailActionToken.TOKEN_TYPE)
.assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
realmRep.setAttributes(originalAttributes);
managedRealm.admin().update(realmRep);
}
@@ -806,7 +806,7 @@ public class RequiredActionEmailVerificationTest extends AbstractTestRealmKeyclo
events.poll();
try {
setTimeOffset(3600);
timeOffSet.set(3600);
driver.manage().deleteAllCookies();
@@ -824,7 +824,7 @@ public class RequiredActionEmailVerificationTest extends AbstractTestRealmKeyclo
.detail(Details.ACTION, VerifyEmailActionToken.TOKEN_TYPE)
.assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
}
}
@@ -1191,14 +1191,14 @@ public class RequiredActionEmailVerificationTest extends AbstractTestRealmKeyclo
String verificationUrl = getEmailLink(message);
try {
setTimeOffset(360);
timeOffSet.set(360);
driver.navigate().to(verificationUrl.trim());
loginPage.assertCurrent();
assertEquals("Action expired. Please start again.", loginPage.getError());
} finally {
setTimeOffset(0);
timeOffSet.set(0);
}
}
@@ -212,7 +212,7 @@ public class RequiredActionResetPasswordTest extends AbstractTestRealmKeycloakTe
try {
RealmManager.realm(managedRealm.admin()).passwordPolicy("forceExpiredPasswordChange(1)");
setTimeOffset(60 * 60 * 48);
timeOffSet.set(60 * 60 * 48);
//create username only flow
testingClient.server("test").run(session -> FlowUtil.inCurrentRealm(session).copyBrowserFlow(newFlowAlias));
@@ -239,7 +239,7 @@ public class RequiredActionResetPasswordTest extends AbstractTestRealmKeycloakTe
.ifPresent(authenticationFlowRepresentation ->
managedRealm.admin().flows().deleteFlow(authenticationFlowRepresentation.getId()));
setTimeOffset(0);
timeOffSet.set(0);
RealmManager.realm(managedRealm.admin()).passwordPolicy(null);
}
}
@@ -703,7 +703,7 @@ public class RequiredActionUpdateEmailTestWithVerificationTest extends AbstractR
try {
// Move time forward beyond cooldown period (default 30 seconds)
setTimeOffset(40);
timeOffSet.set(40);
// Logout and login again to retry after cooldown
managedRealm.admin().users().get(testUser.getId()).logout();
@@ -715,7 +715,7 @@ public class RequiredActionUpdateEmailTestWithVerificationTest extends AbstractR
updateEmailPage.changeEmail("newemail@localhost");
assertEquals(2, mail.getReceivedMessages().length, "Second email should be sent after cooldown expires");
} finally {
setTimeOffset(0);
timeOffSet.set(0);
}
}
}
@@ -163,7 +163,7 @@ public abstract class AbstractServletsAdapterTest extends AbstractAdapterTest {
}
protected void setAdapterAndServerTimeOffset(int timeOffset, String... servletUris) {
setTimeOffset(timeOffset);
timeOffSet.set(timeOffset);
for (String servletUri : servletUris) {
setAdapterServletTimeOffset(timeOffset, servletUri);
@@ -51,7 +51,7 @@ public abstract class AbstractSAMLServletAdapterTest extends AbstractServletsAda
}
protected void setAdapterAndServerTimeOffset(int timeOffset, String... servletUris) {
setTimeOffset(timeOffset);
timeOffSet.set(timeOffset);
Arrays.stream(servletUris)
.map(url -> url += "unsecured")
@@ -2137,10 +2137,10 @@ public class EntitlementAPITest extends AbstractAuthzTest {
AccessToken accessTokenToken = toAccessToken(authorizationResponse.getToken());
assertEquals(refreshToken.getExp() - refreshToken.getIat(), 1800);
assertEquals(accessTokenToken.getExp() - accessTokenToken.getIat(), 300);
setTimeOffset(i);
timeOffSet.set(i);
}
} finally {
resetTimeOffset();
timeOffSet.set(0);
}
}
@@ -126,7 +126,7 @@ public class KcOIDCBrokerWithSignatureTest extends AbstractBaseBrokerTest {
AccountHelper.logout(adminClient.realm(bc.consumerRealmName()), bc.getUserLogin());
// Set time offset. New keys can be downloaded. Check that user is able to login.
setTimeOffset(20);
timeOffSet.set(20);
logInAsUserInIDPWithReAuthenticate();
appPage.assertCurrent();
@@ -187,7 +187,7 @@ public class KcOIDCBrokerWithSignatureTest extends AbstractBaseBrokerTest {
AccountHelper.logout(adminClient.realm(bc.consumerRealmName()), bc.getUserLogin());
// Even after time offset is user not able to login, because it uses old key hardcoded in identityProvider config
setTimeOffset(20);
timeOffSet.set(20);
logInAsUserInIDPWithReAuthenticate();
assertErrorPage("Unexpected error when authenticating with identity provider");
@@ -466,7 +466,7 @@ public class KcOIDCBrokerWithSignatureTest extends AbstractBaseBrokerTest {
Assertions.assertFalse(cache.contains(expectedCacheKey));
// Check that user is not able to login with IDP
setTimeOffset(20);
timeOffSet.set(20);
logInAsUserInIDP();
assertErrorPage("Unexpected error when authenticating with identity provider");
}
@@ -411,7 +411,7 @@ public class KcOidcBrokerIdpLinkActionTest extends AbstractInitializedBaseBroker
Response response = AccountHelper.addIdentityProvider(adminClient.realm(bc.consumerRealmName()), "user1", adminClient.realm(bc.providerRealmName()), bc.getUserLogin(), bc.getIDPAlias());
Assertions.assertEquals(204, response.getStatus());
setTimeOffset(2);
timeOffSet.set(2);
// Enforce re-authentication on "consumer" realm. Try to do re-authentication with the use of IDP, but reject consent screen on IDP side
oauth.loginForm().maxAge(1).open();
@@ -65,7 +65,7 @@ public class KcOidcBrokerLogoutFrontChannelTest extends AbstractKcOidcBrokerLogo
int expiresInMs = (int) (idToken.getExp() - idToken.getIat());
// simulate token expiration
setTimeOffset(expiresInMs * 2);
timeOffSet.set(expiresInMs * 2);
logoutFromRealm(
getConsumerRoot(),
@@ -130,7 +130,7 @@ public class KcOidcBrokerLogoutTest extends AbstractKcOidcBrokerLogoutTest {
int expiresInMs = (int) (idToken.getExp() - idToken.getIat());
// simulate token expiration
setTimeOffset(expiresInMs * 2);
timeOffSet.set(expiresInMs * 2);
logoutFromRealm(
getConsumerRoot(),
@@ -70,7 +70,7 @@ public class KcOidcBrokerPassMaxAgeTest extends AbstractBrokerTest {
loginPage.login(bc.getUserLogin(), bc.getUserPassword());
setTimeOffset(2);
timeOffSet.set(2);
// trigger re-auth with max_age while we are still authenticated
String loginUrlWithMaxAge = getLoginUrl(getConsumerRoot(), bc.consumerRealmName(), "account") + "&max_age=1";
@@ -120,7 +120,7 @@ public class KcOidcBrokerPassMaxAgeTest extends AbstractBrokerTest {
idpResource.update(idpRep);
setTimeOffset(2);
timeOffSet.set(2);
// trigger re-auth with max_age while we are still authenticated
String loginUrlWithMaxAge = getLoginUrl(getConsumerRoot(), bc.consumerRealmName(), "account") + "&max_age=1";
@@ -249,7 +249,7 @@ public class KcOidcBrokerTokenExchangeTest extends AbstractInitializedBaseBroker
return session.getProvider(UserProvider.class, JpaRealmProviderFactory.PROVIDER_ID).getFederatedIdentity(realm, user, idpAlias).getToken();
}, String.class);
setTimeOffset(expires + 10);
timeOffSet.set(expires + 10);
tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken());
assertThat(tokenResponse.getError(), nullValue());
@@ -427,7 +427,7 @@ public class KcOidcBrokerTokenExchangeTest extends AbstractInitializedBaseBroker
exchangeToIdP(brokerApp, tokenResponse.getAccessToken(), expires);
setTimeOffset(expires - IdentityProviderModel.DEFAULT_MIN_VALIDITY_TOKEN);
timeOffSet.set(expires - IdentityProviderModel.DEFAULT_MIN_VALIDITY_TOKEN);
tokenResponse = oauth.doRefreshTokenRequest(tokenResponse.getRefreshToken());
assertThat(tokenResponse.getError(), nullValue());
@@ -628,7 +628,7 @@ public final class KcOidcBrokerTransientSessionsTest extends AbstractAdvancedBro
String newRefreshTokenString = testRefreshWithOfflineToken(token, offlineToken, offlineTokenString, sessionId, consumerRealmRep, lwUserId);
// Change offset to very big value to ensure offline session expires
setTimeOffset(3000000);
timeOffSet.set(3000000);
AccessTokenResponse response = oauth.doRefreshTokenRequest(newRefreshTokenString);
RefreshToken newRefreshToken = oauth.parseRefreshToken(newRefreshTokenString);
@@ -643,14 +643,14 @@ public final class KcOidcBrokerTransientSessionsTest extends AbstractAdvancedBro
.clearDetails()
.assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
}
}
private String testRefreshWithOfflineToken(AccessToken oldToken, RefreshToken offlineToken, String offlineTokenString,
final String sessionId, RealmRepresentation consumerRealmRep, String userId) {
// Change offset to big value to ensure userSession expired
setTimeOffset(99999);
timeOffSet.set(99999);
assertFalse(oldToken.isActive());
assertTrue(offlineToken.isActive());
@@ -690,7 +690,7 @@ public final class KcOidcBrokerTransientSessionsTest extends AbstractAdvancedBro
.assertEvent();
Assertions.assertNotEquals(oldToken.getId(), refreshEvent.getDetails().get(Details.TOKEN_ID));
setTimeOffset(0);
timeOffSet.set(0);
return newRefreshToken;
}
@@ -62,7 +62,7 @@ public class KcOidcBrokerWithConsentTest extends AbstractInitializedBaseBrokerTe
loginPage.login(bc.getUserLogin(), bc.getUserPassword());
// Set time offset
invokeTimeOffset(60);
timeOffSet.set(60);
try {
// User rejected consent
grantPage.assertCurrent();
@@ -72,7 +72,7 @@ public class KcOidcBrokerWithConsentTest extends AbstractInitializedBaseBrokerTe
Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());
} finally {
invokeTimeOffset(0);
timeOffSet.set(0);
}
}
@@ -87,7 +87,7 @@ public class KcOidcBrokerWithConsentTest extends AbstractInitializedBaseBrokerTe
logInWithBroker(bc);
// Set time offset
invokeTimeOffset(60);
timeOffSet.set(60);
try {
testingClient.server(bc.providerRealmName()).run(removeBrokerExpiredSessions());
@@ -98,7 +98,7 @@ public class KcOidcBrokerWithConsentTest extends AbstractInitializedBaseBrokerTe
// Assert login page with "You took too long to login..." message
Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());
} finally {
invokeTimeOffset(0);
timeOffSet.set(0);
}
}
@@ -88,7 +88,7 @@ public class KcOidcMultipleTabsBrokerTest extends AbstractInitializedBaseBroker
Assertions.assertTrue(loginPage.isCurrent("consumer"));
getLogger().infof("URL in tab2: %s", driver.getCurrentUrl());
setTimeOffset(7200000);
timeOffSet.set(7200000);
// Finish login in tab2
loginPage.clickSocial(bc.getIDPAlias());
@@ -128,7 +128,7 @@ public class KcOidcMultipleTabsBrokerTest extends AbstractInitializedBaseBroker
Assertions.assertTrue(loginPage.isCurrent("consumer"));
getLogger().infof("URL in tab2: %s", driver.getCurrentUrl());
setTimeOffset(7200000);
timeOffSet.set(7200000);
// Finish login in tab2
loginPage.clickSocial(bc.getIDPAlias());
@@ -204,7 +204,7 @@ public class KcOidcMultipleTabsBrokerTest extends AbstractInitializedBaseBroker
Assertions.assertTrue(loginPage.isCurrent("consumer"));
getLogger().infof("URL in tab2: %s", driver.getCurrentUrl());
setTimeOffset(7200000);
timeOffSet.set(7200000);
// Finish login in tab2
loginPage.clickSocial(bc.getIDPAlias());
@@ -280,7 +280,7 @@ public class KcOidcMultipleTabsBrokerTest extends AbstractInitializedBaseBroker
Assertions.assertTrue(loginPage.isCurrent("consumer"));
getLogger().infof("URL in tab2: %s", driver.getCurrentUrl());
setTimeOffset(3600);
timeOffSet.set(3600);
// Finish login in tab2
logInWithBroker(bc);
@@ -67,7 +67,7 @@ public class KcSamlBrokerAllowedClockSkewTest extends AbstractInitializedBaseBro
.login().user(bc.getUserLogin(), bc.getUserPassword()).build()
.addStep(() -> KcSamlBrokerAllowedClockSkewTest.this.setTimeOffset(-30)) // offset to the past to invalidate the request
.addStep(() -> KcSamlBrokerAllowedClockSkewTest.this.timeOffSet.set(-30)) // offset to the past to invalidate the request
.processSamlResponse(SamlClient.Binding.POST) // Response from producer IdP should fail
.build()
.execute(hr -> assertThat(hr, statusCodeIsHC(Response.Status.BAD_REQUEST)));
@@ -93,7 +93,7 @@ public class KcSamlBrokerAllowedClockSkewTest extends AbstractInitializedBaseBro
.login().user(bc.getUserLogin(), bc.getUserPassword()).build()
.addStep(() -> KcSamlBrokerAllowedClockSkewTest.this.setTimeOffset(-30)) // offset to the past but inside the clock skew
.addStep(() -> KcSamlBrokerAllowedClockSkewTest.this.timeOffSet.set(-30)) // offset to the past but inside the clock skew
.processSamlResponse(SamlClient.Binding.POST) // Response from producer IdP expired but valid with the clock skew
.build()
@@ -107,4 +107,4 @@ public class KcSamlBrokerAllowedClockSkewTest extends AbstractInitializedBaseBro
assertThat(samlResponse.getSamlObject(), isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
}
}
}
}
@@ -560,7 +560,7 @@ public final class KcSamlBrokerTest extends AbstractAdvancedBrokerTest {
builder = builder.addStepBuilder(new ModifySamlResponseStepBuilder(Binding.POST, builder) {
@Override
protected HttpUriRequest createRequest(URI locationUri, String attributeName, String samlDoc, List<NameValuePair> parameters) throws Exception {
setTimeOffset(10);
timeOffSet.set(10);
return super.createRequest(locationUri, attributeName, samlDoc, parameters);
}
}).build();
@@ -571,7 +571,7 @@ public final class KcSamlBrokerTest extends AbstractAdvancedBrokerTest {
assertThat(hr, bodyHC(Matchers.containsString("Invalid requester")));
});
} finally {
setTimeOffset(0);
timeOffSet.set(0);
}
}
@@ -122,7 +122,7 @@ public class KcSamlMetadataSignedAndEncryptedBrokerTest extends AbstractKcSamlMe
doSamlLoginError(SamlClient.Binding.POST);
// ofsset to allow the refresh of the key
setTimeOffset(35);
timeOffSet.set(35);
doSamlPostLogin();
}
@@ -144,11 +144,11 @@ public class KcSamlMetadataSignedAndEncryptedBrokerTest extends AbstractKcSamlMe
doSamlLoginError(SamlClient.Binding.REDIRECT);
// offset of 35 is not enough (REDIRECT require iteration of keys)
setTimeOffset(35);
timeOffSet.set(35);
doSamlLoginError(SamlClient.Binding.REDIRECT);
// offset more than one day
setTimeOffset(24*60*60 + 5);
timeOffSet.set(24*60*60 + 5);
doSamlRedirectLogin();
}
}
@@ -172,11 +172,11 @@ public class KcSamlMetadataSignedAndEncryptedBrokerTest extends AbstractKcSamlMe
doSamlLoginError(SamlClient.Binding.REDIRECT);
// offset of 35 is not enough (REDIRECT require iteration of keys)
setTimeOffset(35);
timeOffSet.set(35);
doSamlLoginError(SamlClient.Binding.REDIRECT);
// offset more than one hour defined in the descriptor
setTimeOffset(3600 + 5);
timeOffSet.set(3600 + 5);
doSamlRedirectLogin();
}
}
@@ -196,7 +196,7 @@ public class KcSamlMetadataSignedAndEncryptedBrokerTest extends AbstractKcSamlMe
doSamlPostLogin(Response.Status.BAD_REQUEST.getStatusCode(), null, this::identityDocument);
// offset one day to force refresh and use the new encryption key
setTimeOffset(24*60*60 + 5);
timeOffSet.set(24*60*60 + 5);
doSamlPostLogin();
}
@@ -219,7 +219,7 @@ public class KcSamlMetadataSignedAndEncryptedBrokerTest extends AbstractKcSamlMe
doSamlPostLogin(Response.Status.BAD_REQUEST.getStatusCode(), null, this::identityDocument);
// offset 1h to force refresh and use the new encryption key
setTimeOffset(3600 + 5);
timeOffSet.set(3600 + 5);
doSamlPostLogin();
}
}
@@ -105,7 +105,7 @@ public class KcSamlMetadataSignedBrokerTest extends AbstractKcSamlMetadataBroker
doSamlPostLogin(Status.BAD_REQUEST.getStatusCode(), "Invalid signature in response from identity provider", this::identityDocument);
// ofsset to allow the refresh of the key
setTimeOffset(35);
timeOffSet.set(35);
doSamlPostLogin(Status.OK.getStatusCode(), "Update Account Information", this::identityDocument);
}
@@ -119,7 +119,7 @@ public class KcSamlMetadataSignedBrokerTest extends AbstractKcSamlMetadataBroker
doSamlPostLogin(Status.BAD_REQUEST.getStatusCode(), "Invalid signature in response from identity provider", this::removeKeyNameFromSignature);
// ofsset to allow the refresh of the key
setTimeOffset(35);
timeOffSet.set(35);
doSamlPostLogin(Status.OK.getStatusCode(), "Update Account Information", this::removeKeyNameFromSignature);
}
@@ -140,11 +140,11 @@ public class KcSamlMetadataSignedBrokerTest extends AbstractKcSamlMetadataBroker
doSamlRedirectLogin(Status.BAD_REQUEST.getStatusCode(), "Invalid signature in response from identity provider");
// offset of 35 is not enough (REDIRECT require iteration of keys)
setTimeOffset(35);
timeOffSet.set(35);
doSamlRedirectLogin(Status.BAD_REQUEST.getStatusCode(), "Invalid signature in response from identity provider.");
// offset more than one day
setTimeOffset(24*60*60 + 5);
timeOffSet.set(24*60*60 + 5);
doSamlRedirectLogin(Status.OK.getStatusCode(), "Update Account Information");
// rotate keys it should fail again
@@ -152,7 +152,7 @@ public class KcSamlMetadataSignedBrokerTest extends AbstractKcSamlMetadataBroker
doSamlRedirectLogin(Status.BAD_REQUEST.getStatusCode(), "Invalid signature in response from identity provider");
// manually refresh after 1d plus 20s (15s more min refresh is 10s)
setTimeOffset(24*60*60 + 20);
timeOffSet.set(24*60*60 + 20);
Assertions.assertTrue(adminClient.realm(bc.consumerRealmName()).identityProviders().get(bc.getIDPAlias()).reloadKeys());
doSamlRedirectLogin(Status.OK.getStatusCode(), "Update Account Information");
}
@@ -178,11 +178,11 @@ public class KcSamlMetadataSignedBrokerTest extends AbstractKcSamlMetadataBroker
doSamlRedirectLogin(Status.BAD_REQUEST.getStatusCode(), "Invalid signature in response from identity provider");
// offset of 35 is not enough (REDIRECT require iteration of keys)
setTimeOffset(35);
timeOffSet.set(35);
doSamlRedirectLogin(Status.BAD_REQUEST.getStatusCode(), "Invalid signature in response from identity provider.");
// offset more than one hour set as cache duration in the realm
setTimeOffset(3600 + 5);
timeOffSet.set(3600 + 5);
doSamlRedirectLogin(Status.OK.getStatusCode(), "Update Account Information");
// rotate keys it should fail again
@@ -190,7 +190,7 @@ public class KcSamlMetadataSignedBrokerTest extends AbstractKcSamlMetadataBroker
doSamlRedirectLogin(Status.BAD_REQUEST.getStatusCode(), "Invalid signature in response from identity provider");
// manually refresh after 1d plus 20s (15s more min refresh is 10s)
setTimeOffset(3600 + 20);
timeOffSet.set(3600 + 20);
Assertions.assertTrue(adminClient.realm(bc.consumerRealmName()).identityProviders().get(bc.getIDPAlias()).reloadKeys());
doSamlRedirectLogin(Status.OK.getStatusCode(), "Update Account Information");
}
@@ -80,7 +80,7 @@ public class KcSamlMultipleTabsBrokerTest extends AbstractInitializedBaseBrokerT
Assertions.assertTrue(loginPage.isCurrent("consumer"));
getLogger().infof("URL in tab2: %s", driver.getCurrentUrl());
setTimeOffset(7200000);
timeOffSet.set(7200000);
// Finish login in tab2
loginPage.clickSocial(bc.getIDPAlias());
@@ -147,7 +147,7 @@ public class KcSamlMultipleTabsBrokerTest extends AbstractInitializedBaseBrokerT
Assertions.assertTrue(loginPage.isCurrent("consumer"));
getLogger().infof("URL in tab2: %s", driver.getCurrentUrl());
setTimeOffset(3600);
timeOffSet.set(3600);
// Finish login in tab2
logInWithBroker(bc);
@@ -610,7 +610,7 @@ public class CIBATest extends AbstractClientPoliciesTest {
String codeId = loginEvent.getDetails().get(Details.CODE_ID);
String userId = loginEvent.getUserId();
setTimeOffset(3);
timeOffSet.set(3);
tokenRes = doBackchannelAuthenticationTokenRequest(username, response.getAuthReqId());
@@ -673,7 +673,7 @@ public class CIBATest extends AbstractClientPoliciesTest {
String codeId = loginEvent.getDetails().get(Details.CODE_ID);
String userId = loginEvent.getUserId();
setTimeOffset(5);
timeOffSet.set(5);
// user Token Request again
tokenRes = doBackchannelAuthenticationTokenRequest(username, response.getAuthReqId());
@@ -1196,7 +1196,7 @@ public class CIBATest extends AbstractClientPoliciesTest {
// user Authentication Channel completed
doAuthenticationChannelCallback(authenticationChannelReq);
setTimeOffset(6);
timeOffSet.set(6);
// user Token Request after Authentication Channel completion
tokenRes = oauth.ciba().doBackchannelAuthenticationTokenRequest(response.getAuthReqId());
@@ -1242,7 +1242,7 @@ public class CIBATest extends AbstractClientPoliciesTest {
// user Authentication Channel completed
doAuthenticationChannelCallback(authenticationChannelReq);
setTimeOffset(70);
timeOffSet.set(70);
// user Token Request before Authentication Channel completion
AccessTokenResponse tokenRes = oauth.ciba().doBackchannelAuthenticationTokenRequest(response.getAuthReqId());
@@ -1281,7 +1281,7 @@ public class CIBATest extends AbstractClientPoliciesTest {
// user Authentication Channel Request
TestAuthenticationChannelRequest authenticationChannelReq = doAuthenticationChannelRequest("3FIekcs9");
setTimeOffset(70);
timeOffSet.set(70);
int statusCode = oauth.ciba().doAuthenticationChannelCallback(authenticationChannelReq.getBearerToken(), SUCCEED);
assertThat(statusCode, is(equalTo(Status.FORBIDDEN.getStatusCode())));
@@ -117,7 +117,7 @@ public class ClientSecretRotationTest extends AbstractRestServiceTest {
} catch (ClientPolicyException e) {
throw new RuntimeException(e);
}
resetTimeOffset();
timeOffSet.set(0);
}
@Override
@@ -260,7 +260,7 @@ public class ClientSecretRotationTest extends AbstractRestServiceTest {
configureDefaultProfileAndPolicy();
//advance 1 hour
setTimeOffset(3600);
timeOffSet.set(3600);
String newSecret = clientResource.generateNewSecret().getValue();
assertThat(newSecret, not(equalTo(secondSecret)));
@@ -299,7 +299,7 @@ public class ClientSecretRotationTest extends AbstractRestServiceTest {
logger.debug("Current time " + Time.toDate(Time.currentTime()));
//advance 1 hour
setTimeOffset(3601);
timeOffSet.set(3601);
logger.debug("Time after offset " + Time.toDate(Time.currentTime()));
clientRepresentation = clientResource.toRepresentation();
@@ -366,7 +366,7 @@ public class ClientSecretRotationTest extends AbstractRestServiceTest {
oauth.doLogout(res.getRefreshToken());
//advance 1 hour
setTimeOffset(3601);
timeOffSet.set(3601);
oauth.client(clientId, DEFAULT_SECRET);
@@ -399,7 +399,7 @@ public class ClientSecretRotationTest extends AbstractRestServiceTest {
clientResource.update(clientRepresentation);
//advance 1 hour
setTimeOffset(3601);
timeOffSet.set(3601);
// force client update (rotate the secret according to the policy)
clientRepresentation = clientResource.toRepresentation();
@@ -453,7 +453,7 @@ public class ClientSecretRotationTest extends AbstractRestServiceTest {
logger.debug(">>> secret creation time " + Time.toDate(Time.currentTime()));
setTimeOffset(3601);
timeOffSet.set(3601);
clientResource.update(clientResource.toRepresentation());
logger.debug(">>> secret expiration time after first update " + Time.toDate(
@@ -475,7 +475,7 @@ public class ClientSecretRotationTest extends AbstractRestServiceTest {
oauth.client(clientId);
setTimeOffset(7201);
timeOffSet.set(7201);
logger.debug("client secret:" + updatedSecret + "\nsecret expiration: " + Time.toDate(
wrapper.getClientSecretExpirationTime()) + "\nrotated secret: "
@@ -512,7 +512,7 @@ public class ClientSecretRotationTest extends AbstractRestServiceTest {
clientResource.update(clientResource.toRepresentation());
//advance 1 hour
setTimeOffset(3601);
timeOffSet.set(3601);
// force client update (rotate the secret according to the policy)
String firstSecret = clientResource.getSecret().getValue();
@@ -59,7 +59,7 @@ public class InitialAccessTokenTest extends AbstractClientRegistrationTest {
ClientRepresentation rep = new ClientRepresentation();
setTimeOffset(10);
timeOffSet.set(10);
ClientRepresentation created = reg.create(rep);
Assertions.assertNotNull(created);
@@ -123,7 +123,7 @@ public class InitialAccessTokenTest extends AbstractClientRegistrationTest {
ClientRepresentation rep = new ClientRepresentation();
setTimeOffset(10);
timeOffSet.set(10);
try {
reg.create(rep);
@@ -288,7 +288,7 @@ public class OIDCJwksClientRegistrationTest extends AbstractClientRegistrationTe
// Error should happen. KeyStorageProvider won't yet download new keys because of timeout
assertAuthenticateClientError(generatedKeys2, response, KEEP_GENERATED_KID);
setTimeOffset(20);
timeOffSet.set(20);
// Now new keys should be successfully downloaded
assertAuthenticateClientSuccess(generatedKeys2, response, KEEP_GENERATED_KID);
@@ -83,7 +83,7 @@ public class RegistrationAccessTokenTest extends AbstractClientRegistrationTest
@Test
public void getClientWithRegistrationToken() throws ClientRegistrationException {
setTimeOffset(10);
timeOffSet.set(10);
ClientRepresentation rep = reg.get(client.getClientId());
assertNotNull(rep);
@@ -449,7 +449,7 @@ public abstract class AbstractClientPoliciesTest extends AbstractKeycloakTest {
clientResource.update(clientRepresentation);
// set time offset, so that new keys are downloaded
setTimeOffset(20);
timeOffSet.set(20);
return keyPair;
}
@@ -1105,7 +1105,7 @@ public class ClientPoliciesTest extends AbstractClientPoliciesTest {
assertThat(updated.getClientSecretExpiresAt(), equalTo(firstSecretExpiration));
//force secret expiration
setTimeOffset(61);
timeOffSet.set(61);
updateClientDynamically(clientId, (OIDCClientRepresentation clientRep) -> clientRep.setClientName(generateSuffixedName(CLIENT_NAME)));
@@ -1123,7 +1123,7 @@ public class ClientPoliciesTest extends AbstractClientPoliciesTest {
assertLoginAndLogoutStatus(clientId, firstSecret, Response.Status.OK);
//force rotated secret expiration
setTimeOffset(100);
timeOffSet.set(100);
//login with updated secret (remains valid)
assertLoginAndLogoutStatus(clientId, updatedSecret, Response.Status.OK);
@@ -1156,7 +1156,7 @@ public class ClientPoliciesTest extends AbstractClientPoliciesTest {
assertThat(firstSecretExpiration, is(greaterThan(Time.currentTime())));
//Enter in Remaining expiration window
setTimeOffset(41);
timeOffSet.set(41);
//update client to force rotation (due to remaining expiration)
updateClientDynamically(clientId, (OIDCClientRepresentation clientRep) -> clientRep.setContacts(Collections.singletonList("keycloak@keycloak.org")));
@@ -99,7 +99,7 @@ public class LDAPExternalChangesTest extends AbstractLDAPTest {
tokenResponse = oauth.doPasswordGrantRequest(originalEmail, "Password1");
assertTrue(tokenResponse.isSuccess());
setTimeOffset(610);
timeOffSet.set(610);
tokenResponse = oauth.doPasswordGrantRequest(originalEmail, "Password1");
assertFalse(tokenResponse.isSuccess());
@@ -149,7 +149,7 @@ public class LDAPExternalChangesTest extends AbstractLDAPTest {
tokenResponse = oauth.doPasswordGrantRequest(originalUsername, "Password1");
assertTrue(tokenResponse.isSuccess());
setTimeOffset(610);
timeOffSet.set(610);
tokenResponse = oauth.doPasswordGrantRequest(originalUsername, "Password1");
assertFalse(tokenResponse.isSuccess());
@@ -1406,7 +1406,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest {
LDAPTestUtils.removeLDAPUserByUsername(ldapProvider, appRealm, ldapProvider.getLdapIdentityStore().getConfig(), "johndirect");
});
setTimeOffset(60 * 5); // 5 minutes in future, user should be cached still
timeOffSet.set(60 * 5); // 5 minutes in future, user should be cached still
testingClient.server().run(session -> {
RealmModel appRealm = new RealmManager(session).getRealmByName("test");
@@ -1418,7 +1418,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest {
Assertions.assertEquals("johndirect@email.org", email);
});
setTimeOffset(60 * 20); // 20 minutes into future, cache will be invalidated
timeOffSet.set(60 * 20); // 20 minutes into future, cache will be invalidated
testingClient.server().run(session -> {
RealmModel appRealm = new RealmManager(session).getRealmByName("test");
@@ -1427,7 +1427,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest {
Assertions.assertNull(user);
});
} finally {
resetTimeOffset();
timeOffSet.set(0);
testingClient.testing().revertTestingInfinispanTimeService();
}
}
@@ -1474,21 +1474,21 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest {
Assertions.assertTrue(testedUser instanceof CachedUserModel);
});
setTimeOffset(60 * 5); // 5 minutes in future, should be cached still
timeOffSet.set(60 * 5); // 5 minutes in future, should be cached still
testingClient.server().run(session -> {
RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME);
UserModel testedUser = session.users().getUserById(appRealm, userId);
Assertions.assertTrue(testedUser instanceof CachedUserModel);
});
setTimeOffset(60 * 10); // 10 minutes into future, cache will be invalidated
timeOffSet.set(60 * 10); // 10 minutes into future, cache will be invalidated
testingClient.server().run(session -> {
RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME);
UserModel testedUser = session.users().getUserByUsername(appRealm, "thor");
Assertions.assertFalse(testedUser instanceof CachedUserModel);
});
setTimeOffset(0);
timeOffSet.set(0);
}
@Test
@@ -1520,7 +1520,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest {
Assertions.assertEquals("Doe", john.getLastName());
// expire the cache which is 10 minutes
setTimeOffset(610);
timeOffSet.set(610);
// new sn should be present
users = managedRealm.admin().users().search("johnkeycloak", true);
@@ -1537,7 +1537,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest {
johnLdapObject.setSingleAttribute(LDAPConstants.SN, "Doe");
ctx.getLdapProvider().getLdapIdentityStore().update(johnLdapObject);
});
resetTimeOffset();
timeOffSet.set(0);
testingClient.testing().revertTestingInfinispanTimeService();
}
}
@@ -335,7 +335,7 @@ public class ClientStorageTest extends AbstractTestRealmKeycloakTest {
realm.updateComponent(model);
});
testIsCached();
setTimeOffset(2 * 60 * 60); // 2 hours in future
timeOffSet.set(2 * 60 * 60); // 2 hours in future
testNotCached();
testIsCached();
@@ -360,9 +360,9 @@ public class ClientStorageTest extends AbstractTestRealmKeycloakTest {
realm.updateComponent(model);
});
testIsCached();
setTimeOffset(2 * 24 * 60 * 60); // 2 days in future
timeOffSet.set(2 * 24 * 60 * 60); // 2 days in future
testIsCached();
setTimeOffset(5 * 24 * 60 * 60); // 5 days in future
timeOffSet.set(5 * 24 * 60 * 60); // 5 days in future
testNotCached();
testIsCached();
@@ -384,11 +384,11 @@ public class ClientStorageTest extends AbstractTestRealmKeycloakTest {
});
testIsCached();
setTimeOffset(1/2 * 60 * 60); // 1/2 hour in future
timeOffSet.set(1/2 * 60 * 60); // 1/2 hour in future
testIsCached();
setTimeOffset(2 * 60 * 60); // 2 hours in future
timeOffSet.set(2 * 60 * 60); // 2 hours in future
testNotCached();
testIsCached();
@@ -496,7 +496,7 @@ public class ClientStorageTest extends AbstractTestRealmKeycloakTest {
private String testRefreshWithOfflineToken(AccessToken oldToken, RefreshToken offlineToken, String offlineTokenString,
final String sessionId, String userId) {
// Change offset to big value to ensure userSession expired
setTimeOffset(99999);
timeOffSet.set(99999);
Assertions.assertFalse(oldToken.isActive());
Assertions.assertTrue(offlineToken.isActive());
@@ -537,7 +537,7 @@ public class ClientStorageTest extends AbstractTestRealmKeycloakTest {
.assertEvent();
Assertions.assertNotEquals(oldToken.getId(), refreshEvent.getDetails().get(Details.TOKEN_ID));
setTimeOffset(0);
timeOffSet.set(0);
return newRefreshToken;
}
@@ -394,7 +394,7 @@ public class UserStorageFailureTest extends AbstractTestRealmKeycloakTest {
try {
// force cache to expire
setTimeOffset(Math.toIntExact(Duration.ofMinutes(10).toSeconds()));
timeOffSet.set(Math.toIntExact(Duration.ofMinutes(10).toSeconds()));
user = managedRealm.admin().users().search(FailableHardcodedStorageProvider.username).get(0);
assertFalse(user.isEnabled());
toggleForceFailOnValidation(false);
@@ -402,7 +402,7 @@ public class UserStorageFailureTest extends AbstractTestRealmKeycloakTest {
assertTrue(user.isEnabled());
// force cache to expire again and make sure user is disabled
setTimeOffset(Math.toIntExact(Duration.ofMinutes(20).toSeconds()));
timeOffSet.set(Math.toIntExact(Duration.ofMinutes(20).toSeconds()));
toggleForceFailOnValidation(true);
user = managedRealm.admin().users().search(FailableHardcodedStorageProvider.username).get(0);
assertFalse(user.isEnabled());
@@ -417,7 +417,7 @@ public class UserStorageFailureTest extends AbstractTestRealmKeycloakTest {
user = managedRealm.admin().users().search(FailableHardcodedStorageProvider.username).get(0);
assertTrue(user.isEnabled());
} finally {
resetTimeOffset();
timeOffSet.set(0);
toggleForceFailOnValidation(false);
}
}
@@ -198,7 +198,7 @@ public class UserStorageTest extends AbstractAuthTest {
Assertions.assertNotNull(userMapStorageFactory);
userMapStorageFactory.clear();
});
resetTimeOffset();
timeOffSet.set(0);
testingClient.testing().revertTestingInfinispanTimeService();
}
@@ -689,11 +689,11 @@ public class UserStorageTest extends AbstractAuthTest {
setFirstname("thor", "Thor1");
setTimeOffset(2 * 24 * 60 * 60); // 2 days in future
timeOffSet.set(2 * 24 * 60 * 60); // 2 days in future
validateFirstname("thor", "Thor0"); // should still be cached
setTimeOffset(5 * 24 * 60 * 60); // 5 days in future
timeOffSet.set(5 * 24 * 60 * 60); // 5 days in future
validateFirstname("thor", "Thor1"); // should be evicted
@@ -719,11 +719,11 @@ public class UserStorageTest extends AbstractAuthTest {
validateFirstname("thor", "Thor0"); // should still be cached
setTimeOffset(30 * 60); // 1/2 hour in future
timeOffSet.set(30 * 60); // 1/2 hour in future
validateFirstname("thor", "Thor0"); // should still be cached
setTimeOffset(2 * 60 * 60); // 2 hours in future
timeOffSet.set(2 * 60 * 60); // 2 hours in future
validateFirstname("thor", "Thor1"); // should be evicted
@@ -543,7 +543,7 @@ public class BruteForceTest extends AbstractChangeImportedUserPasswordsTest {
//Wait for brute force executor to process the login and then wait for delta time
WaitUtils.waitForBruteForceExecutors(testingClient);
setTimeOffset(5);
timeOffSet.set(5);
loginInvalidPassword();
loginSuccess();
@@ -560,7 +560,7 @@ public class BruteForceTest extends AbstractChangeImportedUserPasswordsTest {
//Wait for brute force executor to process the login and then wait for delta time
WaitUtils.waitForBruteForceExecutors(testingClient);
setTimeOffset(realm.getMaxDeltaTimeSeconds());
timeOffSet.set(realm.getMaxDeltaTimeSeconds());
String realmId = realm.getId();
testingClient.server().run(session -> {
@@ -582,7 +582,7 @@ public class BruteForceTest extends AbstractChangeImportedUserPasswordsTest {
//Wait for brute force executor to process the login and then wait for delta time
WaitUtils.waitForBruteForceExecutors(testingClient);
setTimeOffset(5);
timeOffSet.set(5);
loginInvalidPassword();
expectPermanentlyDisabled();
@@ -606,7 +606,7 @@ public class BruteForceTest extends AbstractChangeImportedUserPasswordsTest {
// KEYCLOAK-5420
// Test to make sure that temporarily disabled doesn't increment failure count
setTimeOffset(21);
timeOffSet.set(21);
// should be unlocked now
loginSuccess();
clearUserFailures();
@@ -640,14 +640,14 @@ public class BruteForceTest extends AbstractChangeImportedUserPasswordsTest {
loginInvalidPassword();
expectTemporarilyDisabled();
assertUserNumberOfFailures(user.getId(), 2);
this.setTimeOffset(30);
timeOffSet.set(30);
loginInvalidPassword();
assertUserNumberOfFailures(user.getId(), 3);
this.setTimeOffset(60);
timeOffSet.set(60);
loginSuccess();
} finally {
this.resetTimeOffset();
timeOffSet.set(0);
}
}
@@ -665,18 +665,18 @@ public class BruteForceTest extends AbstractChangeImportedUserPasswordsTest {
loginInvalidPassword();
expectTemporarilyDisabled();
assertUserNumberOfFailures(user.getId(), 2);
this.setTimeOffset(30);
timeOffSet.set(30);
loginInvalidPassword();
assertUserNumberOfFailures(user.getId(), 3);
this.setTimeOffset(60);
timeOffSet.set(60);
expectTemporarilyDisabled();
} finally {
realm.setPermanentLockout(false);
realm.setBruteForceStrategy(RealmRepresentation.BruteForceStrategy.MULTIPLE);
managedRealm.admin().update(realm);
this.resetTimeOffset();
timeOffSet.set(0);
}
}
@@ -736,7 +736,7 @@ public class BruteForceTest extends AbstractChangeImportedUserPasswordsTest {
managedRealm.admin().update(realm);
// expires the temporary lockout
this.setTimeOffset(60);
timeOffSet.set(60);
// after switching to permanent lockout the user status is disabled because there are login failures
// the user did not try to successfully authenticate yet to clear the login failures
@@ -758,7 +758,7 @@ public class BruteForceTest extends AbstractChangeImportedUserPasswordsTest {
// login failures should be removed after re-enabling the user and the user able to authenticate
loginSuccess();
} finally {
resetTimeOffset();
timeOffSet.set(0);
realm.setPermanentLockout(false);
managedRealm.admin().update(realm);
}
@@ -929,11 +929,11 @@ public class BruteForceTest extends AbstractChangeImportedUserPasswordsTest {
loginInvalidPassword();
loginInvalidPassword();
expectTemporarilyDisabled();
setTimeOffset(21);
timeOffSet.set(21);
loginInvalidPassword();
expectTemporarilyDisabled();
setTimeOffset(42);
timeOffSet.set(42);
loginInvalidPassword();
expectPermanentlyDisabled();
@@ -958,7 +958,7 @@ public class BruteForceTest extends AbstractChangeImportedUserPasswordsTest {
loginInvalidPassword();
loginInvalidPassword();
expectTemporarilyDisabled();
setTimeOffset(21);
timeOffSet.set(21);
UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0);
Map<String, Object> status = adminClient.realm("test").attackDetection().bruteForceUserStatus(user.getId());
assertEquals(1, status.get("numTemporaryLockouts"));
@@ -610,14 +610,14 @@ public class LevelOfAssuranceFlowTest extends AbstractChangeImportedUserPassword
assertLoggedInWithAcr("3");
// Time offset to 210
setTimeOffset(210);
timeOffSet.set(210);
// Re-auth 2: Should return level 2 (gold) due level 3 expired
oauth.openLoginForm();
assertLoggedInWithAcr("gold");
// Time offset to 310
setTimeOffset(310);
timeOffSet.set(310);
// Re-auth 3: Should return level 0 (copper) due levels 1 and 2 expired
oauth.openLoginForm();
@@ -642,7 +642,7 @@ public class LevelOfAssuranceFlowTest extends AbstractChangeImportedUserPassword
assertLoggedInWithAcr("3");
// Time offset to 210
setTimeOffset(210);
timeOffSet.set(210);
// Re-auth 2: Should ask user for re-authentication with level2 and level3. Level1 did not yet expired and should be automatic
openLoginFormWithAcrClaim(true, "3");
@@ -651,7 +651,7 @@ public class LevelOfAssuranceFlowTest extends AbstractChangeImportedUserPassword
assertLoggedInWithAcr("3");
// Time offset to 310
setTimeOffset(310);
timeOffSet.set(310);
// Re-auth 3: Should ask user for re-authentication with level1. Level2 and Level3 did not yet expired and should be automatic
openLoginFormWithAcrClaim(true, "3");
@@ -695,7 +695,7 @@ public class LevelOfAssuranceFlowTest extends AbstractChangeImportedUserPassword
authenticateWithUsernamePassword();
assertLoggedInWithAcr("silver");
setTimeOffset(120);
timeOffSet.set(120);
// Change condition configuration to 60
@@ -539,7 +539,7 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
try {
// Setting offset to more than one day to force password update
// elapsedTime > timeToExpire
setTimeOffset(86405);
timeOffSet.set(86405);
oauth.openLoginForm();
@@ -550,7 +550,7 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
final String newPwd = generatePassword("login-test");
updatePasswordPage.changePassword(newPwd, newPwd);
setTimeOffset(0);
timeOffSet.set(0);
events.expectRequiredAction(EventType.UPDATE_PASSWORD).detail(Details.CREDENTIAL_TYPE, PasswordCredentialModel.TYPE).user(userId).detail(Details.USERNAME, "login-test").assertEvent();
events.expectRequiredAction(EventType.UPDATE_CREDENTIAL).detail(Details.CREDENTIAL_TYPE, PasswordCredentialModel.TYPE).user(userId).detail(Details.USERNAME, "login-test").assertEvent();
@@ -573,7 +573,7 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
try {
// Setting offset to less than one day to avoid forced password update
// elapsedTime < timeToExpire
setTimeOffset(86205);
timeOffSet.set(86205);
oauth.openLoginForm();
@@ -582,7 +582,7 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
Assertions.assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType());
Assertions.assertNotNull(oauth.parseLoginResponse().getCode());
setTimeOffset(0);
timeOffSet.set(0);
EventAssertion.expectLoginSuccess(events.poll()).userId(userId).details(Details.USERNAME, "login-test");
} finally {
@@ -594,11 +594,11 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
public void loginNoTimeoutWithLongWait() {
oauth.openLoginForm();
setTimeOffset(1700);
timeOffSet.set(1700);
loginPage.login("login-test", getPassword("login-test"));
setTimeOffset(0);
timeOffSet.set(0);
EventAssertion.expectLoginSuccess(events.poll()).userId(userId).details(Details.USERNAME, "login-test");
}
@@ -817,13 +817,13 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
public void loginExpiredCode() {
oauth.openLoginForm();
// authSession expired and removed from the storage
setTimeOffset(5000);
timeOffSet.set(5000);
loginPage.login("login@test.com", getPassword("login-test"));
loginPage.assertCurrent();
Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());
setTimeOffset(0);
timeOffSet.set(0);
EventAssertion.assertError(events.poll()).type(EventType.LOGIN_ERROR).userId(null).sessionId(null).error(Errors.EXPIRED_CODE);
}
@@ -832,7 +832,7 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
@Test
public void loginExpiredCodeWithExplicitRemoveExpired() {
oauth.openLoginForm();
setTimeOffset(5000);
timeOffSet.set(5000);
loginPage.login("login@test.com", getPassword("login-test"));
@@ -840,7 +840,7 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
Assertions.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());
setTimeOffset(0);
timeOffSet.set(0);
EventAssertion.assertError(events.poll()).type(EventType.LOGIN_ERROR).userId(null).sessionId(null).error(Errors.EXPIRED_CODE)
.details(Details.RESTART_AFTER_TIMEOUT, "true");
@@ -860,7 +860,7 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
EventAssertion.expectLoginSuccess(events.poll()).userId(userId);
// wait for a timeout
setTimeOffset(6);
timeOffSet.set(6);
oauth.openLoginForm();
loginPage.login("login@test.com", getPassword("login-test"));
@@ -957,7 +957,7 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
public void openLoginFormAfterExpiredCode() throws Exception {
oauth.openLoginForm();
setTimeOffset(5000);
timeOffSet.set(5000);
oauth.openLoginForm();
@@ -987,7 +987,7 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
Assertions.assertEquals((Integer) 1, getTestingClient().testing().getAuthenticationSessionTabsCount("test", authSessionId));
// authentication session should be expired after 1 minute
setTimeOffset(300);
timeOffSet.set(300);
Assertions.assertEquals((Integer) 0, getTestingClient().testing().getAuthenticationSessionTabsCount("test", authSessionId));
}
@@ -1013,7 +1013,7 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
appPage.assertCurrent();
// expire idle timeout using the timeout window.
setTimeOffset(2 + (ProfileAssume.isFeatureEnabled(Profile.Feature.PERSISTENT_USER_SESSIONS) ? 0 : SessionTimeoutHelper.IDLE_TIMEOUT_WINDOW_SECONDS));
timeOffSet.set(2 + (ProfileAssume.isFeatureEnabled(Profile.Feature.PERSISTENT_USER_SESSIONS) ? 0 : SessionTimeoutHelper.IDLE_TIMEOUT_WINDOW_SECONDS));
// trying to open the account page with an expired idle timeout should redirect back to the login page.
oauth.openLoginForm();
@@ -1041,7 +1041,7 @@ public class LoginTest extends AbstractChangeImportedUserPasswordsTest {
appPage.assertCurrent();
// expire the max lifespan.
setTimeOffset(2);
timeOffSet.set(2);
// trying to open the account page with an expired lifespan should redirect back to the login page.
oauth.openLoginForm();
@@ -223,7 +223,7 @@ public class MultipleTabsLoginTest extends AbstractChangeImportedUserPasswordsTe
loginPage.assertCurrent();
// Wait until authentication session expires
setTimeOffset(7200000);
timeOffSet.set(7200000);
loginPage.login("login-test", getPassword("login-test"));
loginPage.assertCurrent();
@@ -268,7 +268,7 @@ public class MultipleTabsLoginTest extends AbstractChangeImportedUserPasswordsTe
loginPage.assertCurrent();
getLogger().info("URL in tab2: " + driver.getCurrentUrl());
// Wait until authentication session expires
setTimeOffset(7200000);
timeOffSet.set(7200000);
//triggers the postponed function in authChecker.js to check if the auth session cookie has changed
WaitUtils.pause(2000);
@@ -360,7 +360,7 @@ public class MultipleTabsLoginTest extends AbstractChangeImportedUserPasswordsTe
getLogger().info("URL in tab2: " + driver.getCurrentUrl());
// Wait until authentication session expires
setTimeOffset(7200000);
timeOffSet.set(7200000);
//triggers the postponed function in authChecker.js to check if the auth session cookie has changed
WaitUtils.pause(2000);
@@ -399,7 +399,7 @@ public class MultipleTabsLoginTest extends AbstractChangeImportedUserPasswordsTe
getLogger().info("URL in tab2: " + driver.getCurrentUrl());
// Wait until authentication session expires
setTimeOffset(7200000);
timeOffSet.set(7200000);
//triggers the postponed function in authChecker.js to check if the auth session cookie has changed
WaitUtils.pause(2000);
@@ -775,7 +775,7 @@ public class MultipleTabsLoginTest extends AbstractChangeImportedUserPasswordsTe
getLogger().info("URL in tab2: " + driver.getCurrentUrl());
// Wait until authentication session expires
setTimeOffset(7200000);
timeOffSet.set(7200000);
//triggers the postponed function in authChecker.js to check if the auth session cookie has changed
WaitUtils.pause(2000);
@@ -823,7 +823,7 @@ public class MultipleTabsLoginTest extends AbstractChangeImportedUserPasswordsTe
loginPage.assertCurrent();
getLogger().info("URL in tab2: " + driver.getCurrentUrl());
// Wait until authentication session expires
setTimeOffset(7200000);
timeOffSet.set(7200000);
//triggers the postponed function in authChecker.js to check if the auth session cookie has changed
WaitUtils.pause(2000);
@@ -875,7 +875,7 @@ public class MultipleTabsLoginTest extends AbstractChangeImportedUserPasswordsTe
getLogger().info("URL in tab2: " + driver.getCurrentUrl());
// Wait until authentication session expires
setTimeOffset(7200000);
timeOffSet.set(7200000);
//triggers the postponed function in authChecker.js to check if the auth session cookie has changed
WaitUtils.pause(2000);
@@ -133,7 +133,7 @@ public class ReAuthenticationTest extends AbstractChangeImportedUserPasswordsTes
Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
// Set time offset
setTimeOffset(10);
timeOffSet.set(10);
// Request re-authentication
oauth.loginForm().maxAge(1).open();
@@ -172,7 +172,7 @@ public class ReAuthenticationTest extends AbstractChangeImportedUserPasswordsTes
Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
// Set time offset
setTimeOffset(10);
timeOffSet.set(10);
// Request re-authentication
oauth.loginForm().maxAge(1).open();
@@ -219,7 +219,7 @@ public class ReAuthenticationTest extends AbstractChangeImportedUserPasswordsTes
Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
// Set time offset
setTimeOffset(10);
timeOffSet.set(10);
// Request re-authentication
oauth.loginForm().maxAge(1).open();
@@ -262,7 +262,7 @@ public class ReAuthenticationTest extends AbstractChangeImportedUserPasswordsTes
Assertions.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
// See that user can re-authenticate with the github link present on the page as user has link to github social provider
setTimeOffset(10);
timeOffSet.set(10);
oauth.loginForm().maxAge(1).open();
// Username input hidden as well as register and rememberMe. Info message should be present
@@ -330,7 +330,7 @@ public class ReAuthenticationTest extends AbstractChangeImportedUserPasswordsTes
AccessTokenResponse response1 = oauth.doAccessTokenRequest(code);
//set time offset after user session expiration (10s) but before accessCodeLifespanLogin (1800s) and accessCodeLifespan (60s)
setTimeOffset(20);
timeOffSet.set(20);
oauth.openLoginForm();
loginPage.login("john-doh@localhost", getPassword("john-doh@localhost"));
@@ -344,7 +344,7 @@ public class ReAuthenticationTest extends AbstractChangeImportedUserPasswordsTes
Assertions.assertNotEquals(accessToken1.getSubject(), accessToken2.getSubject());
Assertions.assertNotEquals(accessToken1.getSessionId(), accessToken2.getSessionId());
setTimeOffset(0);
timeOffSet.set(0);
rep.setSsoSessionIdleTimeout(originalSsoSessionIdleTimeout);
rep.setSsoSessionMaxLifespan(originalSsoSessionMaxLifespan);
realmsResouce().realm(rep.getRealm()).update(rep);
@@ -689,7 +689,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
try {
setTimeOffset(360);
timeOffSet.set(360);
driver.navigate().to(changePasswordUrl.trim());
@@ -699,7 +699,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
}
}
@@ -725,7 +725,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
setTimeOffset(70);
timeOffSet.set(70);
driver.navigate().to(changePasswordUrl.trim());
@@ -735,7 +735,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
realmRep.setActionTokenGeneratedByUserLifespan(originalValue.get());
managedRealm.admin().update(realmRep);
@@ -763,7 +763,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
setTimeOffset(70);
timeOffSet.set(70);
driver.navigate().to(changePasswordUrl.trim());
@@ -773,7 +773,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
realmRep.setAttributes(originalAttributes);
managedRealm.admin().update(realmRep);
@@ -803,7 +803,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
setTimeOffset(70);
timeOffSet.set(70);
driver.navigate().to(changePasswordUrl.trim());
@@ -813,7 +813,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
realmRep.setAttributes(originalAttributes);
managedRealm.admin().update(realmRep);
@@ -846,7 +846,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
log.debug("Removing cookies."); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path
driver.manage().deleteAllCookies();
setTimeOffset(70);
timeOffSet.set(70);
log.debug("Going to reset password URI.");
driver.navigate().to(changePasswordUrl.trim());
@@ -858,7 +858,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
realmRep.setActionTokenGeneratedByUserLifespan(originalValue.get());
managedRealm.admin().update(realmRep);
@@ -889,7 +889,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
log.debug("Removing cookies."); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path
driver.manage().deleteAllCookies();
setTimeOffset(70);
timeOffSet.set(70);
log.debug("Going to reset password URI.");
URLUtils.navigateToUri(changePasswordUrl.trim());
@@ -901,7 +901,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
realmRep.setAttributes(originalAttributes);
managedRealm.admin().update(realmRep);
@@ -933,7 +933,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
log.debug("Removing cookies."); // This is necessary to delete KC_RESTART cookie that is restricted to /auth/realms/test path
driver.manage().deleteAllCookies();
setTimeOffset(70);
timeOffSet.set(70);
log.debug("Going to reset password URI.");
driver.navigate().to(changePasswordUrl.trim());
@@ -945,7 +945,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
realmRep.setAttributes(originalAttributes);
managedRealm.admin().update(realmRep);
@@ -985,7 +985,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
setTimeOffset(70);
timeOffSet.set(70);
driver.navigate().to(changePasswordUrl.trim());
@@ -995,7 +995,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
realmRep.setActionTokenGeneratedByUserLifespan(originalValue.get());
managedRealm.admin().update(realmRep);
@@ -1033,7 +1033,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
setTimeOffset(70);
timeOffSet.set(70);
driver.navigate().to(changePasswordUrl.trim());
@@ -1043,7 +1043,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
realmRep.setAttributes(originalAttributes);
managedRealm.admin().update(realmRep);
@@ -1082,7 +1082,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
String changePasswordUrl = MailUtils.getPasswordResetEmailLink(message);
setTimeOffset(70);
timeOffSet.set(70);
driver.navigate().to(changePasswordUrl.trim());
@@ -1092,7 +1092,7 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
events.expectRequiredAction(EventType.EXECUTE_ACTION_TOKEN_ERROR).error("expired_code").client((String) null).user(userId).session((String) null).clearDetails().detail(Details.ACTION, ResetCredentialsActionToken.TOKEN_TYPE).assertEvent();
} finally {
setTimeOffset(0);
timeOffSet.set(0);
realmRep.setAttributes(originalAttributes);
managedRealm.admin().update(realmRep);
@@ -1258,28 +1258,28 @@ public class ResetPasswordTest extends AbstractTestRealmKeycloakTest {
setPasswordPolicy("passwordHistory");
try {
setTimeOffset(2000000);
timeOffSet.set(2000000);
resetPassword("login-test", "password1");
resetPasswordInvalidPassword("login-test", "password1", "Invalid password: must not be equal to any of last 3 passwords.");
setTimeOffset(4000000);
timeOffSet.set(4000000);
resetPassword("login-test", "password2");
resetPasswordInvalidPassword("login-test", "password1", "Invalid password: must not be equal to any of last 3 passwords.");
resetPasswordInvalidPassword("login-test", "password2", "Invalid password: must not be equal to any of last 3 passwords.");
setTimeOffset(6000000);
timeOffSet.set(6000000);
resetPassword("login-test", "password3");
resetPasswordInvalidPassword("login-test", "password1", "Invalid password: must not be equal to any of last 3 passwords.");
resetPasswordInvalidPassword("login-test", "password2", "Invalid password: must not be equal to any of last 3 passwords.");
resetPasswordInvalidPassword("login-test", "password3", "Invalid password: must not be equal to any of last 3 passwords.");
setTimeOffset(8000000);
timeOffSet.set(8000000);
resetPassword("login-test", password);
} finally {
setTimeOffset(0);
timeOffSet.set(0);
}
}
@@ -920,7 +920,7 @@ public abstract class AbstractClientAuthSignedJWTTest extends AbstractKeycloakTe
clientResource.update(clientRepresentation);
// set time offset, so that new keys are downloaded
setTimeOffset(20);
timeOffSet.set(20);
return keyPair;
}
@@ -941,7 +941,7 @@ public abstract class AbstractClientAuthSignedJWTTest extends AbstractKeycloakTe
clientResource.update(clientRepresentation);
// set time offset, so that new keys are downloaded
setTimeOffset(20);
timeOffSet.set(20);
return keyPair;
}
@@ -440,13 +440,13 @@ public class AccessTokenTest extends AbstractKeycloakTest {
String code = oauth.parseLoginResponse().getCode();
try {
setTimeOffset(2);
timeOffSet.set(2);
AccessTokenResponse response = oauth.doAccessTokenRequest(code);
Assertions.assertEquals(400, response.getStatusCode());
} finally {
getTestingClient().testing().revertTestingInfinispanTimeService();
resetTimeOffset();
timeOffSet.set(0);
}
AssertEvents.ExpectedEvent expectedEvent = events.expectCodeToToken(codeId, codeId);
@@ -1107,7 +1107,7 @@ public class AccessTokenTest extends AbstractKeycloakTest {
// Assert token expiration equals token lifespan
assertExpiration(response.getExpiresIn(), tokenLifespan);
setTimeOffset(sessionMax - 60);
timeOffSet.set(sessionMax - 60);
response = oauth.doRefreshTokenRequest(response.getRefreshToken());
assertEquals(200, response.getStatusCode());
@@ -405,7 +405,7 @@ public class ClientAuthSecretSignedJWTTest extends AbstractKeycloakTest {
assertThat(firstSecret, not(equalTo(newSecret)));
//force rotated secret expiration
setTimeOffset(31);
timeOffSet.set(31);
oauth.client("jwt-client");
oauth.doLogin("test-user@localhost", "password");
@@ -623,7 +623,7 @@ public class ClientAuthSignedJWTTest extends AbstractClientAuthSignedJWTTest {
public void testAssertionExpired() throws Exception {
String invalidJwt = getClient1SignedJWT();
setTimeOffset(1000);
timeOffSet.set(1000);
List<NameValuePair> parameters = new LinkedList<NameValuePair>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
@@ -633,7 +633,7 @@ public class ClientAuthSignedJWTTest extends AbstractClientAuthSignedJWTTest {
CloseableHttpResponse resp = sendRequest(oauth.getEndpoints().getToken(), parameters);
AccessTokenResponse response = new AccessTokenResponse(resp);
setTimeOffset(0);
timeOffSet.set(0);
assertError(response, "client1", OAuthErrorException.INVALID_CLIENT, Errors.INVALID_CLIENT_CREDENTIALS);
}
@@ -748,7 +748,7 @@ public class ClientAuthSignedJWTTest extends AbstractClientAuthSignedJWTTest {
public void testAssertionInvalidNotBefore() throws Exception {
String invalidJwt = getClient1SignedJWT();
setTimeOffset(-1000);
timeOffSet.set(-1000);
List<NameValuePair> parameters = new LinkedList<NameValuePair>();
parameters.add(new BasicNameValuePair(OAuth2Constants.GRANT_TYPE, OAuth2Constants.CLIENT_CREDENTIALS));
@@ -758,7 +758,7 @@ public class ClientAuthSignedJWTTest extends AbstractClientAuthSignedJWTTest {
CloseableHttpResponse resp = sendRequest(oauth.getEndpoints().getToken(), parameters);
AccessTokenResponse response = new AccessTokenResponse(resp);
setTimeOffset(0);
timeOffSet.set(0);
assertError(response, "client1", OAuthErrorException.INVALID_CLIENT, Errors.INVALID_CLIENT_CREDENTIALS);
@@ -906,13 +906,13 @@ public class ClientAuthSignedJWTTest extends AbstractClientAuthSignedJWTTest {
assertSuccess(response, app1.getClientId(), serviceAccountUser.getId(), serviceAccountUser.getUsername());
// in the max-exp window the token should be detected as already used
setTimeOffset(30);
timeOffSet.set(30);
response = doClientCredentialsGrantRequest(jwt);
assertError(response, app1.getClientId(), OAuthErrorException.INVALID_CLIENT, Errors.INVALID_CLIENT_CREDENTIALS);
assertThat(response.getErrorDescription(), containsString("Token reuse detected"));
// after the max-exp window the token cannot be used because iat is too far in the past
setTimeOffset(65);
timeOffSet.set(65);
response = doClientCredentialsGrantRequest(jwt);
assertError(response, app1.getClientId(), OAuthErrorException.INVALID_CLIENT, Errors.INVALID_CLIENT_CREDENTIALS);
assertThat(response.getErrorDescription(), containsString("Token was issued too far in the past to be used now"));
@@ -294,13 +294,13 @@ public class DPoPTest extends AbstractTestRealmKeycloakTest {
AccessTokenResponse response = successTokenProceduresWithDPoP(dpopProofEcEncoded, jktEc, true, true, false);
setTimeOffset(25); // 25 <= 10+10+15, proof not expired because clockSkew, detected by replay check
timeOffSet.set(25); // 25 <= 10+10+15, proof not expired because clockSkew, detected by replay check
response = oauth.refreshRequest(response.getRefreshToken()).dpopProof(dpopProofEcEncoded).send();
assertEquals(400, response.getStatusCode());
assertEquals(OAuthErrorException.INVALID_REQUEST, response.getError());
assertEquals("DPoP proof has already been used", response.getErrorDescription());
setTimeOffset(36); // 36 > 10+10+15, proof expired definitely
timeOffSet.set(36); // 36 > 10+10+15, proof expired definitely
response = oauth.refreshRequest(response.getRefreshToken()).dpopProof(dpopProofEcEncoded).send();
assertEquals(400, response.getStatusCode());
assertEquals(response.getError(), OAuthErrorException.INVALID_REQUEST);
@@ -1044,7 +1044,7 @@ public class DPoPTest extends AbstractTestRealmKeycloakTest {
Assertions.assertEquals(REALM_NAME, realm.getRealm());
// To enforce token refresh by admin client in the next request
setTimeOffset(700);
timeOffSet.set(700);
realm = adminClientDPoP.realm(REALM_NAME).toRepresentation();
Assertions.assertEquals(REALM_NAME, realm.getRealm());
@@ -154,7 +154,7 @@ public class LogoutTest extends AbstractKeycloakTest {
oauth.doLogout(refreshToken1);
setTimeOffset(2);
timeOffSet.set(2);
driver.navigate().refresh();
oauth.fillLoginForm("test-user@localhost", "password");
@@ -496,7 +496,7 @@ public class LogoutTest extends AbstractKeycloakTest {
AccessTokenResponse tokenResponse = oauth.accessTokenRequest(code).param(AdapterConstants.CLIENT_SESSION_STATE, "client-session").send();
setTimeOffset(1);
timeOffSet.set(1);
oauth.loginForm()
.prompt(OIDCLoginProtocol.PROMPT_VALUE_LOGIN)
@@ -623,11 +623,11 @@ public class OAuth2DeviceAuthorizationGrantTest extends AbstractKeycloakTest {
Assertions.assertEquals(5, response.getInterval());
try {
setTimeOffset(610);
timeOffSet.set(610);
openVerificationPage(response.getVerificationUriComplete());
} finally {
getTestingClient().testing().revertTestingInfinispanTimeService();
resetTimeOffset();
timeOffSet.set(0);
}
// device code not found in the cache because of expiration => invalid_grant error and redirection to the login page
@@ -718,7 +718,7 @@ public class OAuth2DeviceAuthorizationGrantTest extends AbstractKeycloakTest {
Assertions.assertEquals(5, response.getInterval());
try {
setTimeOffset(610);
timeOffSet.set(610);
// Token request from device
AccessTokenResponse tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode());
@@ -726,7 +726,7 @@ public class OAuth2DeviceAuthorizationGrantTest extends AbstractKeycloakTest {
Assertions.assertEquals("invalid_grant", tokenResponse.getError());
} finally {
getTestingClient().testing().revertTestingInfinispanTimeService();
resetTimeOffset();
timeOffSet.set(0);
}
}
@@ -768,14 +768,14 @@ public class OAuth2DeviceAuthorizationGrantTest extends AbstractKeycloakTest {
AccessTokenResponse tokenResponse;
try {
setTimeOffset(100);
timeOffSet.set(100);
// Token request from device
tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode());
Assertions.assertEquals(400, tokenResponse.getStatusCode());
Assertions.assertEquals("authorization_pending", tokenResponse.getError());
setTimeOffset(125);
timeOffSet.set(125);
// Token request from device
tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode());
@@ -783,7 +783,7 @@ public class OAuth2DeviceAuthorizationGrantTest extends AbstractKeycloakTest {
Assertions.assertEquals("expired_token", tokenResponse.getError());
} finally {
getTestingClient().testing().revertTestingInfinispanTimeService();
resetTimeOffset();
timeOffSet.set(0);
}
clientRepresentation.getAttributes().put(OAuth2DeviceConfig.OAUTH2_DEVICE_CODE_LIFESPAN_PER_CLIENT, "");
@@ -828,7 +828,7 @@ public class OAuth2DeviceAuthorizationGrantTest extends AbstractKeycloakTest {
Assertions.assertEquals(400, tokenResponse.getStatusCode());
Assertions.assertEquals("slow_down", tokenResponse.getError());
setTimeOffset(7);
timeOffSet.set(7);
// Token request from device
tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode());
@@ -836,7 +836,7 @@ public class OAuth2DeviceAuthorizationGrantTest extends AbstractKeycloakTest {
Assertions.assertEquals(400, tokenResponse.getStatusCode());
Assertions.assertEquals("slow_down", tokenResponse.getError());
setTimeOffset(10);
timeOffSet.set(10);
// Token request from device
tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode());
@@ -881,7 +881,7 @@ public class OAuth2DeviceAuthorizationGrantTest extends AbstractKeycloakTest {
Assertions.assertEquals("slow_down", tokenResponse.getError());
// Wait the interval
setTimeOffset(5);
timeOffSet.set(5);
// Polling again
tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode());
@@ -908,7 +908,7 @@ public class OAuth2DeviceAuthorizationGrantTest extends AbstractKeycloakTest {
Assertions.assertEquals("authorization_pending", tokenResponse.getError());
// Wait
setTimeOffset(10);
timeOffSet.set(10);
// Polling again without waiting
tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode());
@@ -918,7 +918,7 @@ public class OAuth2DeviceAuthorizationGrantTest extends AbstractKeycloakTest {
Assertions.assertEquals("slow_down", tokenResponse.getError());
// Wait
setTimeOffset(15);
timeOffSet.set(15);
// Polling again
tokenResponse = oauth.device().doDeviceTokenRequest(response.getDeviceCode());
@@ -443,7 +443,7 @@ public class OAuthProofKeyForCodeExchangeTest extends AbstractKeycloakTest {
assertThat(actual, allOf(greaterThanOrEqualTo(1799L - ALLOWED_CLOCK_SKEW), lessThanOrEqualTo(1800L + ALLOWED_CLOCK_SKEW)));
assertEquals(sessionId, refreshToken.getSessionState());
setTimeOffset(2);
timeOffSet.set(2);
AccessTokenResponse refreshResponse = oauth.doRefreshTokenRequest(refreshTokenString);
@@ -479,7 +479,7 @@ public class OAuthProofKeyForCodeExchangeTest extends AbstractKeycloakTest {
Assertions.assertNotEquals(event.getDetails().get(Details.TOKEN_ID), refreshEvent.getDetails().get(Details.TOKEN_ID));
Assertions.assertNotEquals(event.getDetails().get(Details.REFRESH_TOKEN_ID), refreshEvent.getDetails().get(Details.UPDATED_REFRESH_TOKEN_ID));
setTimeOffset(0);
timeOffSet.set(0);
}
// KEYCLOAK-10747 Explicit Proof Key for Code Exchange Activation Settings
@@ -273,7 +273,7 @@ public class RPInitiatedLogoutTest extends AbstractTestRealmKeycloakTest {
String idTokenString = tokenResponse.getIdToken();
// expire online user session
setTimeOffset(9999);
timeOffSet.set(9999);
oauth.logoutForm().postLogoutRedirectUri(APP_REDIRECT_URI).idTokenHint(idTokenString).open();
@@ -386,7 +386,7 @@ public class RPInitiatedLogoutTest extends AbstractTestRealmKeycloakTest {
String idTokenString = tokenResponse.getIdToken();
// Logout should succeed with expired ID token, see KEYCLOAK-3399
setTimeOffset(60 * 60 * 24);
timeOffSet.set(60 * 60 * 24);
String logoutUrl = oauth.logoutForm()
.idTokenHint(idTokenString)
@@ -554,7 +554,7 @@ public class RPInitiatedLogoutTest extends AbstractTestRealmKeycloakTest {
events.assertEmpty();
// Set time offset to expire "action" inside logoutSession
setTimeOffset(310);
timeOffSet.set(310);
logoutConfirmPage.confirmLogout();
errorPage.assertCurrent();
@@ -585,7 +585,7 @@ public class RPInitiatedLogoutTest extends AbstractTestRealmKeycloakTest {
events.assertEmpty();
// Set time offset to expire "action" inside logoutSession
setTimeOffset(1810);
timeOffSet.set(1810);
logoutConfirmPage.confirmLogout();
errorPage.assertCurrent();
@@ -615,7 +615,7 @@ public class RPInitiatedLogoutTest extends AbstractTestRealmKeycloakTest {
events.assertEmpty();
// Set time offset to expire "action" inside logoutSession
setTimeOffset(1810);
timeOffSet.set(1810);
logoutConfirmPage.confirmLogout();
errorPage.assertCurrent();
@@ -688,7 +688,7 @@ public class RPInitiatedLogoutTest extends AbstractTestRealmKeycloakTest {
events.assertEmpty();
// Set time offset to expire "action" inside logoutSession
setTimeOffset(310);
timeOffSet.set(310);
logoutConfirmPage.confirmLogout();
errorPage.assertCurrent();
@@ -596,7 +596,7 @@ public class ResourceOwnerPasswordCredentialsGrantTest extends AbstractKeycloakT
RealmManager.realm(realmResource).passwordPolicy("forceExpiredPasswordChange(1)");
try {
setTimeOffset(60 * 60 * 48);
timeOffSet.set(60 * 60 * 48);
oauth.client("resource-owner", "secret");
@@ -607,7 +607,7 @@ public class ResourceOwnerPasswordCredentialsGrantTest extends AbstractKeycloakT
assertEquals("invalid_grant", response.getError());
assertEquals("Account is not fully set up", response.getErrorDescription());
setTimeOffset(0);
timeOffSet.set(0);
EventAssertion.assertError(events.poll())
.type(EventType.LOGIN_ERROR)
@@ -629,7 +629,7 @@ public class ResourceOwnerPasswordCredentialsGrantTest extends AbstractKeycloakT
RealmManager.realm(realmResource).passwordPolicy("forceExpiredPasswordChange(1)");
try {
setTimeOffset(60 * 60 * 48);
timeOffSet.set(60 * 60 * 48);
oauth.client("resource-owner", "secret");
@@ -248,7 +248,7 @@ public class TokenIntrospectionTest extends AbstractTestRealmKeycloakTest {
oauth.doLogout(refreshToken1);
events.clear();
setTimeOffset(2);
timeOffSet.set(2);
driver.navigate().refresh();
oauth.fillLoginForm("test-user@localhost", "password");
@@ -441,7 +441,7 @@ public class TokenIntrospectionTest extends AbstractTestRealmKeycloakTest {
String code = oauth.parseLoginResponse().getCode();
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code);
setTimeOffset(86400);
timeOffSet.set(86400);
// "Online" session still exists, but is invalid
accessTokenResponse = oauth.doRefreshTokenRequest(accessTokenResponse.getRefreshToken());
@@ -472,7 +472,7 @@ public class TokenIntrospectionTest extends AbstractTestRealmKeycloakTest {
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code);
accessTokenResponse = oauth.doRefreshTokenRequest(accessTokenResponse.getRefreshToken());
setTimeOffset(1200);
timeOffSet.set(1200);
oauth.client("confidential-cli", "secret1");
TokenMetadataRepresentation rep = oauth.doIntrospectionRefreshTokenRequest(accessTokenResponse.getRefreshToken()).asTokenMetadata();
@@ -481,7 +481,7 @@ public class TokenIntrospectionTest extends AbstractTestRealmKeycloakTest {
assertEquals("test-user@localhost", rep.getUserName());
assertEquals("test-app", rep.getClientId());
setTimeOffset(1200 + 1200);
timeOffSet.set(1200 + 1200);
oauth.client("test-app", "password");
@@ -522,7 +522,7 @@ public class TokenIntrospectionTest extends AbstractTestRealmKeycloakTest {
String code = oauth.parseLoginResponse().getCode();
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code);
setTimeOffset(adminClient.realm(oauth.getRealm()).toRepresentation().getAccessTokenLifespan() + 1);
timeOffSet.set(adminClient.realm(oauth.getRealm()).toRepresentation().getAccessTokenLifespan() + 1);
oauth.client("confidential-cli", "secret1");
TokenMetadataRepresentation rep = oauth.doIntrospectionAccessTokenRequest(accessTokenResponse.getAccessToken()).asTokenMetadata();
@@ -555,7 +555,7 @@ public class TokenIntrospectionTest extends AbstractTestRealmKeycloakTest {
AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code);
setTimeOffset(1);
timeOffSet.set(1);
String loginFormUri = oauth.loginForm()
.param(OIDCLoginProtocol.PROMPT_PARAM, OIDCLoginProtocol.PROMPT_VALUE_LOGIN)
@@ -639,7 +639,7 @@ public class TokenIntrospectionTest extends AbstractTestRealmKeycloakTest {
AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code);
String oldRefreshToken = accessTokenResponse.getRefreshToken();
setTimeOffset(1);
timeOffSet.set(1);
accessTokenResponse = oauth.doRefreshTokenRequest(oldRefreshToken);
@@ -185,11 +185,11 @@ public class TokenRevocationTest extends AbstractKeycloakTest {
assertTrue(oauth.tokenRevocationRequest(tokenResponse.getAccessToken()).accessToken().send().isSuccess());
setTimeOffset(adminClient.realm(oauth.getRealm()).toRepresentation().getAccessTokenLifespan());
timeOffSet.set(adminClient.realm(oauth.getRealm()).toRepresentation().getAccessTokenLifespan());
isAccessTokenDisabled(tokenResponse.getAccessToken(), "test-app");
setTimeOffset(0);
timeOffSet.set(0);
}
@Test
@@ -73,7 +73,7 @@ public class UserInfoEndpointCorsTest extends AbstractKeycloakTest {
AccessTokenResponse accessTokenResponse = oauth.doPasswordGrantRequest("test-user@localhost", "password");
// Set time offset to make sure that userInfo request will be invalid due the expired token
setTimeOffset(600);
timeOffSet.set(600);
ResteasyClient resteasyClient = AdminClientUtil.createResteasyClient();
try {
@@ -357,7 +357,7 @@ public class HoKTest extends AbstractTestRealmKeycloakTest {
assertThat(actual, allOf(greaterThanOrEqualTo(1799L - OAuthProofKeyForCodeExchangeTest.ALLOWED_CLOCK_SKEW), lessThanOrEqualTo(1800L + OAuthProofKeyForCodeExchangeTest.ALLOWED_CLOCK_SKEW)));
assertEquals(sessionId, refreshToken.getSessionState());
setTimeOffset(2);
timeOffSet.set(2);
AccessTokenResponse response = null;
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithDefaultKeyStoreAndTrustStore()) {
@@ -398,7 +398,7 @@ public class HoKTest extends AbstractTestRealmKeycloakTest {
assertThat(actual, allOf(greaterThanOrEqualTo(1799L - OAuthProofKeyForCodeExchangeTest.ALLOWED_CLOCK_SKEW), lessThanOrEqualTo(1800L + OAuthProofKeyForCodeExchangeTest.ALLOWED_CLOCK_SKEW)));
assertEquals(sessionId, refreshToken.getSessionState());
setTimeOffset(2);
timeOffSet.set(2);
AccessTokenResponse response = null;
try (CloseableHttpClient client = MutualTLSUtils.newCloseableHttpClientWithoutKeyStoreAndTrustStore()) {
@@ -458,7 +458,7 @@ public class HoKTest extends AbstractTestRealmKeycloakTest {
Assertions.assertNotEquals(tokenEvent.getDetails().get(Details.TOKEN_ID), refreshEvent.getDetails().get(Details.TOKEN_ID));
Assertions.assertNotEquals(tokenEvent.getDetails().get(Details.REFRESH_TOKEN_ID), refreshEvent.getDetails().get(Details.UPDATED_REFRESH_TOKEN_ID));
setTimeOffset(0);
timeOffSet.set(0);
}
// verify HoK Token - Get UserInfo
@@ -997,7 +997,7 @@ public class ParTest extends AbstractClientPoliciesTest {
// Authorization Request with request_uri of PAR
// remove parameters as query strings of uri
// PAR expired
setTimeOffset(expiresIn + 5);
timeOffSet.set(expiresIn + 5);
oauth.redirectUri(null);
oauth.scope(null);
oauth.responseType(null);
@@ -261,7 +261,7 @@ public class ExternalInternalTokenExchangeV2Test extends AbstractInitializedBase
testingClient.server(BrokerTestConstants.REALM_CONS_NAME).run(ExternalInternalTokenExchangeV2Test::setupRealm);
setTimeOffset(3600);
timeOffSet.set(3600);
testTokenExchange(tokenResponse.getAccessToken(), (tokenExchangeResponse) -> {
assertThat(tokenExchangeResponse.getStatus(), equalTo(400));
@@ -370,7 +370,7 @@ public class StandardTokenExchangeV2Test extends AbstractClientPoliciesTest {
assertUserInfoSuccess(exchangedTokenString, "requester-client", "secret", john.getId());
// assert introspection and user-info works in 10s
setTimeOffset(10);
timeOffSet.set(10);
assertIntrospectSuccess(exchangedTokenString, "requester-client", "secret", john.getId());
assertUserInfoSuccess(exchangedTokenString, "requester-client", "secret", john.getId());
@@ -413,12 +413,12 @@ public class StandardTokenExchangeV2Test extends AbstractClientPoliciesTest {
assertUserInfoSuccess(exchangedTokenString, "requester-client", "secret", john.getId());
// assert introspection and user-info works in 10s
setTimeOffset(10);
timeOffSet.set(10);
assertIntrospectSuccess(exchangedTokenString, "requester-client", "secret", john.getId());
assertUserInfoSuccess(exchangedTokenString, "requester-client", "secret", john.getId());
// move time to be more than the normal expired session value, refresh and request another exchange
setTimeOffset(610);
timeOffSet.set(610);
final AccessTokenResponse refreshResponse = oauth.client("subject-client", "secret").scope(null)
.refreshRequest(initialResponse.getRefreshToken()).send();
assertNull(refreshResponse.getError(), "Error refreshing the initial token: " + refreshResponse.getErrorDescription());
@@ -477,7 +477,7 @@ public class StandardTokenExchangeV2Test extends AbstractClientPoliciesTest {
try (Keycloak keycloak = Keycloak.getInstance(ServerURLs.getAuthServerContextRoot() + "/auth",
TEST, Constants.ADMIN_CLI_CLIENT_ID, response.getAccessToken(), TLSUtils.initializeTLS())) {
assertEquals(TEST, keycloak.realm(TEST).toRepresentation().getRealm());
setTimeOffset(10);
timeOffSet.set(10);
assertEquals(TEST, keycloak.realm(TEST).toRepresentation().getRealm());
realm.deleteSession(exchangedToken.getSessionId(), false);
assertThrows(NotAuthorizedException.class, () -> keycloak.realm(TEST).toRepresentation().getRealm());
@@ -512,7 +512,7 @@ public class StandardTokenExchangeV2Test extends AbstractClientPoliciesTest {
final String accountUrl = ServerURLs.getAuthServerContextRoot() + "/auth/realms/test/account";
assertEquals("john", SimpleHttpDefault.doGet(accountUrl, oauth.httpClient().get())
.auth(response.getAccessToken()).asJson(UserRepresentation.class).getUsername());
setTimeOffset(10);
timeOffSet.set(10);
assertEquals("john", SimpleHttpDefault.doGet(accountUrl, oauth.httpClient().get())
.auth(response.getAccessToken()).asJson(UserRepresentation.class).getUsername());
realm.deleteSession(exchangedToken.getSessionId(), false);
@@ -1006,7 +1006,7 @@ public class StandardTokenExchangeV2Test extends AbstractClientPoliciesTest {
Assertions.assertNotNull(exchangedToken);
// Set time offset
setTimeOffset(10);
timeOffSet.set(10);
// SSO login to "requester-client". Will create client session for "requester-client"
oauth.client("requester-client", "secret").openLoginForm();
@@ -300,7 +300,7 @@ public class AuthenticationMethodReferenceTest extends AbstractOIDCScopeTest{
authenticatePassword("test-user", PASSWORD);
// server time forward by 20 seconds to ensure max age is exceeded
setTimeOffset(20);
timeOffSet.set(20);
Tokens tokens = assertLogin(passwordUserId);
@@ -217,7 +217,7 @@ public class OIDCAdvancedRequestParamsTest extends AbstractTestRealmKeycloakTest
Assertions.assertTrue(authTime <= currentTime && authTime + 3 >= currentTime);
// Set time offset
setTimeOffset(10);
timeOffSet.set(10);
// Assert I need to login again through the login form. But username field is not present
oauth.loginForm().maxAge(1).open();
@@ -249,7 +249,7 @@ public class OIDCAdvancedRequestParamsTest extends AbstractTestRealmKeycloakTest
Assertions.assertTrue(authTime <= currentTime && authTime + 3 >= currentTime);
// Set time offset
setTimeOffset(10);
timeOffSet.set(10);
// Now open login form with maxAge=10000
oauth.loginForm().maxAge(10000).open();
@@ -303,7 +303,7 @@ public class OIDCAdvancedRequestParamsTest extends AbstractTestRealmKeycloakTest
long authTime = idToken.getAuth_time();
// Set time offset
setTimeOffset(10);
timeOffSet.set(10);
// Assert user still logged with previous authTime
oauth.loginForm().prompt("none").open();
@@ -383,7 +383,7 @@ public class OIDCAdvancedRequestParamsTest extends AbstractTestRealmKeycloakTest
IDToken oldIdToken = sendTokenRequestAndGetIDToken(loginEvent);
// Set time offset
setTimeOffset(10);
timeOffSet.set(10);
// SSO login first WITHOUT prompt=login ( Tests KEYCLOAK-5248 )
oauth.openLoginForm();
@@ -396,7 +396,7 @@ public class OIDCAdvancedRequestParamsTest extends AbstractTestRealmKeycloakTest
Assertions.assertEquals(oldIdToken.getAuth_time(), newIdToken.getAuth_time());
// Set time offset
setTimeOffset(20);
timeOffSet.set(20);
// Assert need to re-authenticate with prompt=login
oauth.loginForm().prompt("login").open();
@@ -992,7 +992,7 @@ public class OIDCAdvancedRequestParamsTest extends AbstractTestRealmKeycloakTest
clientResource.update(clientRep);
// set time offset, so that new keys are downloaded
setTimeOffset(20);
timeOffSet.set(20);
// Check signed request_uri will pass
AuthorizationEndpointResponse response = oauth.loginForm().requestUri(requestUri).doLogin("test-user@localhost", "password");
@@ -1037,7 +1037,7 @@ public class OIDCAdvancedRequestParamsTest extends AbstractTestRealmKeycloakTest
clientResource.update(clientRep);
// set time offset, so that new keys are downloaded
setTimeOffset(20);
timeOffSet.set(20);
oauth.realm("test");
oauth.client("test-app", "password");
@@ -585,7 +585,7 @@ public class UserInfoTest extends AbstractKeycloakTest {
try {
AccessTokenResponse accessTokenResponse = executeGrantAccessTokenRequest(client);
setTimeOffset(600);
timeOffSet.set(600);
Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getToken());
@@ -618,7 +618,7 @@ public class UserInfoTest extends AbstractKeycloakTest {
oauth.doLogout(refreshToken1);
events.clear();
setTimeOffset(2);
timeOffSet.set(2);
driver.navigate().refresh();
oauth.fillLoginForm("test-user@localhost", "password");
@@ -1081,7 +1081,7 @@ public class UserInfoTest extends AbstractKeycloakTest {
org.keycloak.testsuite.util.oauth.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code);
setTimeOffset(1);
timeOffSet.set(1);
oauth.loginForm().prompt(OIDCLoginProtocol.PROMPT_VALUE_LOGIN).open();
@@ -527,7 +527,7 @@ public class OrganizationInvitationLinkTest extends AbstractOrganizationTest {
organization.members().inviteUser(email, "Homer", "Simpson").close();
try {
setTimeOffset((int) TimeUnit.DAYS.toSeconds(1));
timeOffSet.set((int) TimeUnit.DAYS.toSeconds(1));
List<OrganizationInvitationRepresentation> list = organization.invitations().list();
assertThat(list, Matchers.hasSize(1));
@@ -540,7 +540,7 @@ public class OrganizationInvitationLinkTest extends AbstractOrganizationTest {
assertThat(driver.getPageSource(), Matchers.containsString("Action expired."));
assertThat(managedRealm.admin().users().searchByEmail(email, true), Matchers.empty());
} finally {
resetTimeOffset();
timeOffSet.set(0);
}
}
@@ -233,12 +233,12 @@ public class OrganizationInvitationManagementTest extends AbstractOrganizationTe
assertThat(invitations, empty());
try {
setTimeOffset(Math.toIntExact(Duration.ofDays(2).toSeconds()));
timeOffSet.set(Math.toIntExact(Duration.ofDays(2).toSeconds()));
invitations =
organization.invitations().list("EXPIRED", null, null, null);
assertThat(invitations, hasSize(1));
} finally {
setTimeOffset(0);
timeOffSet.set(0);
}
invitations =
@@ -155,7 +155,7 @@ public class OrganizationAuthenticationTest extends AbstractOrganizationTest {
appPage.assertCurrent();
try {
setTimeOffset(10);
timeOffSet.set(10);
oauth.realm(bc.consumerRealmName());
oauth.loginForm().maxAge(1).kcAction(RequiredAction.UPDATE_PASSWORD.name()).open();
loginPage.assertCurrent();
@@ -165,7 +165,7 @@ public class OrganizationAuthenticationTest extends AbstractOrganizationTest {
updatePasswordPage.updatePasswords(memberPassword, memberPassword);
appPage.assertCurrent();
} finally {
resetTimeOffset();
timeOffSet.set(0);
}
}
@@ -163,10 +163,10 @@ public class PasswordAgePolicyTest extends AbstractAuthTest {
public void testPasswordHistoryRetrySamePassword() {
setPasswordAgePolicyValue(1);
//set offset to 12h ago
setTimeOffset(-12 * 60 * 60);
timeOffSet.set(-12 * 60 * 60);
resetUserPassword(user, "secret");
//try to set again same password
setTimeOffset(0);
timeOffSet.set(0);
expectBadRequestException(f -> resetUserPassword(user, "secret"));
}
@@ -174,13 +174,13 @@ public class PasswordAgePolicyTest extends AbstractAuthTest {
public void testPasswordHistoryWithTwoPasswordsErrorThrown() {
setPasswordAgePolicyValue(1);
//set offset to 12h ago
setTimeOffset(-12 * 60 * 60);
timeOffSet.set(-12 * 60 * 60);
resetUserPassword(user, "secret");
setTimeOffset(-10 * 60 * 60);
timeOffSet.set(-10 * 60 * 60);
resetUserPassword(user, "secret1");
//try to set again same password after 12h
setTimeOffset(0);
timeOffSet.set(0);
expectBadRequestException(f -> resetUserPassword(user, "secret"));
}
@@ -188,13 +188,13 @@ public class PasswordAgePolicyTest extends AbstractAuthTest {
public void testPasswordHistoryWithTwoPasswords() {
setPasswordAgePolicyValue(1);
//set offset to more than a day ago
setTimeOffset(-24 * 60 * 60 * 2);
timeOffSet.set(-24 * 60 * 60 * 2);
resetUserPassword(user, "secret");
setTimeOffset(-10 * 60 * 60);
timeOffSet.set(-10 * 60 * 60);
resetUserPassword(user, "secret1");
//try to set again same password after 48h
setTimeOffset(0);
timeOffSet.set(0);
resetUserPassword(user, "secret");
}
@@ -202,17 +202,17 @@ public class PasswordAgePolicyTest extends AbstractAuthTest {
public void testPasswordHistoryWithMultiplePasswordsErrorThrown() {
setPasswordAgePolicyValue(30);
//set offset to 29 days, 23:45:00
setTimeOffset(-30 * 24 * 60 * 60 + 15 * 60);
timeOffSet.set(-30 * 24 * 60 * 60 + 15 * 60);
resetUserPassword(user, "secret");
setTimeOffset(-25 * 24 * 60 * 60);
timeOffSet.set(-25 * 24 * 60 * 60);
resetUserPassword(user, "secret1");
setTimeOffset(-20 * 24 * 60 * 60);
timeOffSet.set(-20 * 24 * 60 * 60);
resetUserPassword(user, "secret2");
setTimeOffset(-10 * 24 * 60 * 60);
timeOffSet.set(-10 * 24 * 60 * 60);
resetUserPassword(user, "secret3");
//try to set again same password after 30 days, should throw error, 15 minutes too early
setTimeOffset(0);
timeOffSet.set(0);
expectBadRequestException(f -> resetUserPassword(user, "secret"));
}
@@ -220,17 +220,17 @@ public class PasswordAgePolicyTest extends AbstractAuthTest {
public void testPasswordHistoryWithMultiplePasswords() {
setPasswordAgePolicyValue(30);
//set offset to 30 days and 15 minutes
setTimeOffset(-30 * 24 * 60 * 60 - 5 * 60);
timeOffSet.set(-30 * 24 * 60 * 60 - 5 * 60);
resetUserPassword(user, "secret");
setTimeOffset(-25 * 24 * 60 * 60);
timeOffSet.set(-25 * 24 * 60 * 60);
resetUserPassword(user, "secret1");
setTimeOffset(-20 * 24 * 60 * 60);
timeOffSet.set(-20 * 24 * 60 * 60);
resetUserPassword(user, "secret2");
setTimeOffset(-10 * 24 * 60 * 60);
timeOffSet.set(-10 * 24 * 60 * 60);
resetUserPassword(user, "secret3");
//try to set again same password after 30 days and 15 minutes
setTimeOffset(0);
timeOffSet.set(0);
resetUserPassword(user, "secret");
}
@@ -277,12 +277,12 @@ public class PasswordAgePolicyTest extends AbstractAuthTest {
setPasswordAgePolicyValue(1);
//last 3 passwords
setPasswordHistoryValue(3);
setTimeOffset(daysToSeconds(-2));
timeOffSet.set(daysToSeconds(-2));
resetUserPassword(user, "secret");
resetUserPassword(user, "secret1");
resetUserPassword(user, "secret2");
setTimeOffset(daysToSeconds(0));
timeOffSet.set(daysToSeconds(0));
//password history takes precedence
expectBadRequestException(f -> setPasswordAgePolicyValue("secret"));
}
@@ -293,12 +293,12 @@ public class PasswordAgePolicyTest extends AbstractAuthTest {
setPasswordAgePolicyValue(2);
//last 10 passwords
setPasswordHistoryValue(10);
setTimeOffset(daysToSeconds(-1));
timeOffSet.set(daysToSeconds(-1));
resetUserPassword(user, "secret");
resetUserPassword(user, "secret1");
resetUserPassword(user, "secret2");
setTimeOffset(daysToSeconds(0));
timeOffSet.set(daysToSeconds(0));
//password age takes precedence
expectBadRequestException(f -> setPasswordAgePolicyValue("secret"));
}
@@ -102,7 +102,7 @@ public class ArtifactBindingTest extends AbstractSamlTest {
.build()
.login().user(bburkeUser).build()
.handleArtifact(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST)
.setBeforeStepChecks(() -> setTimeOffset(1000)) // Move in time before resolving the artifact
.setBeforeStepChecks(() -> timeOffSet.set(1000)) // Move in time before resolving the artifact
.build()
.doNotFollowRedirects()
.executeAndTransform(this::getArtifactResponse);
@@ -173,13 +173,13 @@ public class X509BrowserCRLTest extends AbstractX509AuthenticationTest {
Assertions.assertEquals(1, crlRule.getCounter("cached-crl"));
// wait the min time and it should be refreshed now and fail
setTimeOffset(10);
timeOffSet.set(10);
assertLoginFailedDueRevokedCertificate();
AccountHelper.logout(managedRealm.admin(), "test-user@localhost");
Assertions.assertEquals(2, crlRule.getCounter("cached-crl"));
// now it's cached until next update 50 years
setTimeOffset(3600);
timeOffSet.set(3600);
assertLoginFailedDueRevokedCertificate();
AccountHelper.logout(managedRealm.admin(), "test-user@localhost");
Assertions.assertEquals(2, crlRule.getCounter("cached-crl"));
@@ -284,12 +284,12 @@ public class X509DirectGrantTest extends AbstractX509AuthenticationTest {
String cfgId = createConfig(directGrantExecution.getId(), cfg);
Assertions.assertNotNull(cfgId);
setTimeOffset(50 * 365 * 24 * 60 * 60);
timeOffSet.set(50 * 365 * 24 * 60 * 60);
oauth.client("resource-owner", "secret");
AccessTokenResponse response = oauth.doPasswordGrantRequest("", "");
setTimeOffset(0);
timeOffSet.set(0);
assertEquals(401, response.getStatusCode());
assertEquals("invalid_request", response.getError());