Skip to content

fix: backport to core 6.0 #972

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [unreleased]

## [6.0.19] - 2024-03-29

- Fixes userIdMapping queries
- Adds a new required `useDynamicSigningKey` into the request body of `RefreshSessionAPI`
- This enables smooth switching between `useDynamicAccessTokenSigningKey` settings by allowing refresh calls to
change the signing key type of a session

## [6.0.18] - 2024-02-20

- Fixes vulnerabilities in dependencies
Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ compileTestJava { options.encoding = "UTF-8" }
// }
//}

version = "6.0.18"
version = "6.0.19"


repositories {
Expand Down
10 changes: 6 additions & 4 deletions src/main/java/io/supertokens/inmemorydb/Start.java
Original file line number Diff line number Diff line change
Expand Up @@ -511,10 +511,11 @@ public SessionInfo getSessionInfo_Transaction(TenantIdentifier tenantIdentifier,
@Override
public void updateSessionInfo_Transaction(TenantIdentifier tenantIdentifier, TransactionConnection con,
String sessionHandle, String refreshTokenHash2,
long expiry) throws StorageQueryException {
long expiry, boolean useStaticKey) throws StorageQueryException {
Connection sqlCon = (Connection) con.getConnection();
try {
SessionQueries.updateSessionInfo_Transaction(this, sqlCon, tenantIdentifier, sessionHandle, refreshTokenHash2, expiry);
SessionQueries.updateSessionInfo_Transaction(this, sqlCon, tenantIdentifier, sessionHandle,
refreshTokenHash2, expiry, useStaticKey);
} catch (SQLException e) {
throw new StorageQueryException(e);
}
Expand Down Expand Up @@ -2154,10 +2155,11 @@ public boolean updateOrDeleteExternalUserIdInfo(AppIdentifier appIdentifier, Str
}

@Override
public HashMap<String, String> getUserIdMappingForSuperTokensIds(ArrayList<String> userIds)
public HashMap<String, String> getUserIdMappingForSuperTokensIds(AppIdentifier appIdentifier,
ArrayList<String> userIds)
throws StorageQueryException {
try {
return UserIdMappingQueries.getUserIdMappingWithUserIds(this, userIds);
return UserIdMappingQueries.getUserIdMappingWithUserIds(this, appIdentifier, userIds);
} catch (SQLException e) {
throw new StorageQueryException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,18 +124,19 @@ public static SessionInfo getSessionInfo_Transaction(Start start, Connection con

public static void updateSessionInfo_Transaction(Start start, Connection con, TenantIdentifier tenantIdentifier,
String sessionHandle,
String refreshTokenHash2, long expiry)
String refreshTokenHash2, long expiry, boolean useStaticKey)
throws SQLException, StorageQueryException {
String QUERY = "UPDATE " + getConfig(start).getSessionInfoTable()
+ " SET refresh_token_hash_2 = ?, expires_at = ?"
+ " SET refresh_token_hash_2 = ?, expires_at = ?, use_static_key = ?"
+ " WHERE app_id = ? AND tenant_id = ? AND session_handle = ?";

update(con, QUERY, pst -> {
pst.setString(1, refreshTokenHash2);
pst.setLong(2, expiry);
pst.setString(3, tenantIdentifier.getAppId());
pst.setString(4, tenantIdentifier.getTenantId());
pst.setString(5, sessionHandle);
pst.setBoolean(3, useStaticKey);
pst.setString(4, tenantIdentifier.getAppId());
pst.setString(5, tenantIdentifier.getTenantId());
pst.setString(6, sessionHandle);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,9 @@ public static UserIdMapping[] getUserIdMappingWithEitherSuperTokensUserIdOrExter

}

public static HashMap<String, String> getUserIdMappingWithUserIds(Start start, ArrayList<String> userIds)
public static HashMap<String, String> getUserIdMappingWithUserIds(Start start,
AppIdentifier appIdentifier,
ArrayList<String> userIds)
throws SQLException, StorageQueryException {

if (userIds.size() == 0) {
Expand All @@ -124,7 +126,8 @@ public static HashMap<String, String> getUserIdMappingWithUserIds(Start start, A

// No need to filter based on tenantId because the id list is already filtered for a tenant
StringBuilder QUERY = new StringBuilder(
"SELECT * FROM " + Config.getConfig(start).getUserIdMappingTable() + " WHERE supertokens_user_id IN (");
"SELECT * FROM " + Config.getConfig(start).getUserIdMappingTable() + " WHERE app_id = ? AND " +
"supertokens_user_id IN (");
for (int i = 0; i < userIds.size(); i++) {
QUERY.append("?");
if (i != userIds.size() - 1) {
Expand All @@ -134,9 +137,10 @@ public static HashMap<String, String> getUserIdMappingWithUserIds(Start start, A
}
QUERY.append(")");
return execute(start, QUERY.toString(), pst -> {
pst.setString(1, appIdentifier.getAppId());
for (int i = 0; i < userIds.size(); i++) {
// i+1 cause this starts with 1 and not 0
pst.setString(i + 1, userIds.get(i));
// i+2 cause this starts with 1 and not 0, and 1 is the app_id
pst.setString(i + 2, userIds.get(i));
}
}, result -> {
HashMap<String, String> userIdMappings = new HashMap<>();
Expand Down
47 changes: 35 additions & 12 deletions src/main/java/io/supertokens/session/Session.java
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M
accessToken.sessionHandle,
Utils.hashSHA256(accessToken.refreshTokenHash1),
System.currentTimeMillis() +
config.getRefreshTokenValidity());
config.getRefreshTokenValidity(), sessionInfo.useStaticKey);
}
storage.commitTransaction(con);

Expand Down Expand Up @@ -423,7 +423,7 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M
Utils.hashSHA256(accessToken.refreshTokenHash1),
System.currentTimeMillis() + Config.getConfig(tenantIdentifierWithStorage, main)
.getRefreshTokenValidity(),
sessionInfo.lastUpdatedSign);
sessionInfo.lastUpdatedSign, sessionInfo.useStaticKey);
if (!success) {
continue;
}
Expand Down Expand Up @@ -473,7 +473,7 @@ public static SessionInformationHolder refreshSession(Main main, @Nonnull String
UnsupportedJWTSigningAlgorithmException, AccessTokenPayloadError {
try {
return refreshSession(new AppIdentifier(null, null), main, refreshToken, antiCsrfToken,
enableAntiCsrf, accessTokenVersion);
enableAntiCsrf, accessTokenVersion, null);
} catch (TenantOrAppNotFoundException e) {
throw new IllegalStateException(e);
}
Expand All @@ -482,7 +482,8 @@ public static SessionInformationHolder refreshSession(Main main, @Nonnull String
public static SessionInformationHolder refreshSession(AppIdentifier appIdentifier, Main main,
@Nonnull String refreshToken,
@Nullable String antiCsrfToken, boolean enableAntiCsrf,
AccessToken.VERSION accessTokenVersion)
AccessToken.VERSION accessTokenVersion,
Boolean shouldUseStaticKey)
throws StorageTransactionLogicException,
UnauthorisedException, StorageQueryException, TokenTheftDetectedException,
UnsupportedJWTSigningAlgorithmException, AccessTokenPayloadError, TenantOrAppNotFoundException {
Expand All @@ -498,14 +499,15 @@ public static SessionInformationHolder refreshSession(AppIdentifier appIdentifie

return refreshSessionHelper(refreshTokenInfo.tenantIdentifier.withStorage(
StorageLayer.getStorage(refreshTokenInfo.tenantIdentifier, main)),
main, refreshToken, refreshTokenInfo, enableAntiCsrf, accessTokenVersion);
main, refreshToken, refreshTokenInfo, enableAntiCsrf, accessTokenVersion, shouldUseStaticKey);
}

private static SessionInformationHolder refreshSessionHelper(
TenantIdentifierWithStorage tenantIdentifierWithStorage, Main main, String refreshToken,
RefreshToken.RefreshTokenInfo refreshTokenInfo,
boolean enableAntiCsrf,
AccessToken.VERSION accessTokenVersion)
AccessToken.VERSION accessTokenVersion,
Boolean shouldUseStaticKey)
throws StorageTransactionLogicException, UnauthorisedException, StorageQueryException,
TokenTheftDetectedException, UnsupportedJWTSigningAlgorithmException, AccessTokenPayloadError,
TenantOrAppNotFoundException {
Expand All @@ -530,7 +532,16 @@ private static SessionInformationHolder refreshSessionHelper(
throw new UnauthorisedException("Session missing in db or has expired");
}

boolean useStaticKey = shouldUseStaticKey != null ? shouldUseStaticKey : sessionInfo.useStaticKey;

if (sessionInfo.refreshTokenHash2.equals(Utils.hashSHA256(Utils.hashSHA256(refreshToken)))) {
if (useStaticKey != sessionInfo.useStaticKey) {
// We do not update anything except the static key status
storage.updateSessionInfo_Transaction(tenantIdentifierWithStorage, con, sessionHandle,
sessionInfo.refreshTokenHash2, sessionInfo.expiry,
useStaticKey);
}

// at this point, the input refresh token is the parent one.
storage.commitTransaction(con);
String antiCsrfToken = enableAntiCsrf ? UUID.randomUUID().toString() : null;
Expand All @@ -542,7 +553,7 @@ private static SessionInformationHolder refreshSessionHelper(
main, sessionHandle,
sessionInfo.userId, Utils.hashSHA256(newRefreshToken.token),
Utils.hashSHA256(refreshToken), sessionInfo.userDataInJWT, antiCsrfToken,
null, accessTokenVersion, sessionInfo.useStaticKey);
null, accessTokenVersion, useStaticKey);

TokenInfo idRefreshToken = new TokenInfo(UUID.randomUUID().toString(),
newRefreshToken.expiry, newRefreshToken.createdTime);
Expand All @@ -560,13 +571,13 @@ private static SessionInformationHolder refreshSessionHelper(
.equals(sessionInfo.refreshTokenHash2))) {
storage.updateSessionInfo_Transaction(tenantIdentifierWithStorage, con, sessionHandle,
Utils.hashSHA256(Utils.hashSHA256(refreshToken)),
System.currentTimeMillis() + config.getRefreshTokenValidity());
System.currentTimeMillis() + config.getRefreshTokenValidity(), useStaticKey);

storage.commitTransaction(con);

return refreshSessionHelper(tenantIdentifierWithStorage, main, refreshToken,
refreshTokenInfo, enableAntiCsrf,
accessTokenVersion);
accessTokenVersion, shouldUseStaticKey);
}

storage.commitTransaction(con);
Expand Down Expand Up @@ -613,7 +624,19 @@ private static SessionInformationHolder refreshSessionHelper(
throw new UnauthorisedException("Session missing in db or has expired");
}

boolean useStaticKey = shouldUseStaticKey != null ? shouldUseStaticKey : sessionInfo.useStaticKey;

if (sessionInfo.refreshTokenHash2.equals(Utils.hashSHA256(Utils.hashSHA256(refreshToken)))) {
if (sessionInfo.useStaticKey != useStaticKey) {
// We do not update anything except the static key status
boolean success = storage.updateSessionInfo_Transaction(sessionHandle,
sessionInfo.refreshTokenHash2, sessionInfo.expiry,
sessionInfo.lastUpdatedSign, useStaticKey);
if (!success) {
continue;
}
}

// at this point, the input refresh token is the parent one.
String antiCsrfToken = enableAntiCsrf ? UUID.randomUUID().toString() : null;

Expand All @@ -624,7 +647,7 @@ private static SessionInformationHolder refreshSessionHelper(
sessionHandle,
sessionInfo.userId, Utils.hashSHA256(newRefreshToken.token),
Utils.hashSHA256(refreshToken), sessionInfo.userDataInJWT, antiCsrfToken,
null, accessTokenVersion, sessionInfo.useStaticKey);
null, accessTokenVersion, useStaticKey);

TokenInfo idRefreshToken = new TokenInfo(UUID.randomUUID().toString(), newRefreshToken.expiry,
newRefreshToken.createdTime);
Expand All @@ -644,13 +667,13 @@ private static SessionInformationHolder refreshSessionHelper(
Utils.hashSHA256(Utils.hashSHA256(refreshToken)),
System.currentTimeMillis() +
Config.getConfig(tenantIdentifierWithStorage, main).getRefreshTokenValidity(),
sessionInfo.lastUpdatedSign);
sessionInfo.lastUpdatedSign, useStaticKey);
if (!success) {
continue;
}
return refreshSessionHelper(tenantIdentifierWithStorage, main, refreshToken, refreshTokenInfo,
enableAntiCsrf,
accessTokenVersion);
accessTokenVersion, shouldUseStaticKey);
}

throw new TokenTheftDetectedException(sessionHandle, sessionInfo.userId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,8 @@ public static HashMap<String, String> getUserIdMappingForSuperTokensUserIds(
ArrayList<String> userIds)
throws StorageQueryException {
// userIds are already filtered for a tenant, so this becomes a tenant specific operation.
return tenantIdentifierWithStorage.getUserIdMappingStorage().getUserIdMappingForSuperTokensIds(userIds);
return tenantIdentifierWithStorage.getUserIdMappingStorage().getUserIdMappingForSuperTokensIds(
tenantIdentifierWithStorage.toAppIdentifier(), userIds);
}

@TestOnly
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,13 @@ public String getPath() {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
// API is app specific, but session is updated based on tenantId obtained from the refreshToken
SemVer version = super.getVersionFromRequest(req);
JsonObject input = InputParser.parseJsonObjectOrThrowError(req);
String refreshToken = InputParser.parseStringOrThrowError(input, "refreshToken", false);
String antiCsrfToken = InputParser.parseStringOrThrowError(input, "antiCsrfToken", true);
Boolean enableAntiCsrf = InputParser.parseBooleanOrThrowError(input, "enableAntiCsrf", false);
Boolean useDynamicSigningKey = version.greaterThanOrEqualTo(SemVer.v3_0) ?
InputParser.parseBooleanOrThrowError(input, "useDynamicSigningKey", true) : null;
assert enableAntiCsrf != null;
assert refreshToken != null;

Expand All @@ -75,13 +78,13 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I
throw new ServletException(e);
}

SemVer version = super.getVersionFromRequest(req);
try {
AccessToken.VERSION accessTokenVersion = AccessToken.getAccessTokenVersionForCDI(version);

SessionInformationHolder sessionInfo = Session.refreshSession(appIdentifierWithStorage, main,
refreshToken, antiCsrfToken,
enableAntiCsrf, accessTokenVersion);
enableAntiCsrf, accessTokenVersion,
useDynamicSigningKey == null ? null : Boolean.FALSE.equals(useDynamicSigningKey));

if (StorageLayer.getStorage(this.getTenantIdentifierWithStorageFromRequest(req), main).getType() ==
STORAGE_TYPE.SQL) {
Expand Down
6 changes: 6 additions & 0 deletions src/test/java/io/supertokens/test/AuthRecipeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import io.supertokens.storageLayer.StorageLayer;
import io.supertokens.thirdparty.ThirdParty;
import io.supertokens.usermetadata.UserMetadata;
import io.supertokens.version.Version;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
Expand Down Expand Up @@ -488,6 +489,8 @@ public void randomPaginationTest() throws Exception {
fail();
}

boolean isMySQL = Version.getVersion(process.getProcess()).getPluginName().equals("mysql");

for (int limit : limits) {

// now we paginate in asc order
Expand All @@ -497,6 +500,9 @@ public void randomPaginationTest() throws Exception {
if (o1.timeJoined != o2.timeJoined) {
return (int) (o1.timeJoined - o2.timeJoined);
}
if (isMySQL) {
return o1.id.compareTo(o2.id);
}
return o2.id.compareTo(o1.id);
});

Expand Down
Loading
Loading