Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix: session creation - checking tenant for user #1063

Open
wants to merge 4 commits into
base: 9.3
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
8 changes: 8 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]


## [9.3.1]

- Adds support for CDI 5.3
- In CDI 5.3, when creating a new session for a known user, checks if the user is a member of that tenant.
If not, returns USER_DOES_NOT_BELONG_TO_TENANT_ERROR.

## [9.3.0]

### Changes
Expand Down Expand Up @@ -149,6 +156,7 @@ CREATE TABLE IF NOT EXISTS oauth_logout_challenges (

CREATE INDEX oauth_logout_challenges_time_created_index ON oauth_logout_challenges(time_created ASC, app_id ASC);
```
>>>>>>> origin/master
Copy link
Collaborator

Choose a reason for hiding this comment

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

merge error?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

it is. Sorry I missed this

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done


## [9.2.3] - 2024-10-09

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 = "9.3.0"
version = "9.3.1"


repositories {
Expand Down
3 changes: 2 additions & 1 deletion coreDriverInterfaceSupported.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"4.0",
"5.0",
"5.1",
"5.2"
"5.2",
"5.3"
]
}
27 changes: 20 additions & 7 deletions src/main/java/io/supertokens/session/Session.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.google.gson.JsonObject;
import io.supertokens.Main;
import io.supertokens.ProcessState;
import io.supertokens.authRecipe.AuthRecipe;
import io.supertokens.config.Config;
import io.supertokens.config.CoreConfig;
import io.supertokens.exceptions.AccessTokenPayloadError;
Expand Down Expand Up @@ -82,7 +83,7 @@ public static SessionInformationHolder createNewSession(TenantIdentifier tenantI
JWT.JWTException, UnsupportedJWTSigningAlgorithmException, AccessTokenPayloadError {
try {
return createNewSession(tenantIdentifier, storage, main, recipeUserId, userDataInJWT, userDataInDatabase,
false, AccessToken.getLatestVersion(), false);
false, AccessToken.getLatestVersion(), false, false);
} catch (TenantOrAppNotFoundException e) {
throw new IllegalStateException(e);
}
Expand All @@ -101,8 +102,9 @@ public static SessionInformationHolder createNewSession(Main main,
try {
return createNewSession(
new TenantIdentifier(null, null, null), storage, main,
recipeUserId, userDataInJWT, userDataInDatabase, false, AccessToken.getLatestVersion(), false);
} catch (TenantOrAppNotFoundException e) {
recipeUserId, userDataInJWT, userDataInDatabase, false,
AccessToken.getLatestVersion(), false, false);
} catch (TenantOrAppNotFoundException | UnauthorisedException e) {
throw new IllegalStateException(e);
}
}
Expand All @@ -121,8 +123,8 @@ public static SessionInformationHolder createNewSession(Main main, @Nonnull Stri
try {
return createNewSession(
new TenantIdentifier(null, null, null), storage, main,
recipeUserId, userDataInJWT, userDataInDatabase, enableAntiCsrf, version, useStaticKey);
} catch (TenantOrAppNotFoundException e) {
recipeUserId, userDataInJWT, userDataInDatabase, enableAntiCsrf, version, useStaticKey, false);
} catch (TenantOrAppNotFoundException | UnauthorisedException e) {
throw new IllegalStateException(e);
}
}
Expand All @@ -132,11 +134,11 @@ public static SessionInformationHolder createNewSession(TenantIdentifier tenantI
@Nonnull JsonObject userDataInJWT,
@Nonnull JsonObject userDataInDatabase,
boolean enableAntiCsrf, AccessToken.VERSION version,
boolean useStaticKey)
boolean useStaticKey, boolean checkUserForTenant)
throws NoSuchAlgorithmException, StorageQueryException, InvalidKeyException,
InvalidKeySpecException, StorageTransactionLogicException, SignatureException, IllegalBlockSizeException,
BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException, AccessTokenPayloadError,
UnsupportedJWTSigningAlgorithmException, TenantOrAppNotFoundException {
UnsupportedJWTSigningAlgorithmException, TenantOrAppNotFoundException, UnauthorisedException {
String sessionHandle = UUID.randomUUID().toString();
if (!tenantIdentifier.getTenantId().equals(TenantIdentifier.DEFAULT_TENANT_ID)) {
sessionHandle += "_" + tenantIdentifier.getTenantId();
Expand All @@ -151,6 +153,7 @@ public static SessionInformationHolder createNewSession(TenantIdentifier tenantI
recipeUserId = userIdMapping.superTokensUserId;
}


primaryUserId = StorageUtils.getAuthRecipeStorage(storage)
.getPrimaryUserIdStrForUserId(tenantIdentifier.toAppIdentifier(), recipeUserId);
if (primaryUserId == null) {
Expand All @@ -166,6 +169,16 @@ public static SessionInformationHolder createNewSession(TenantIdentifier tenantI
if (userIdMappings.containsKey(recipeUserId)) {
recipeUserId = userIdMappings.get(recipeUserId);
}

if(checkUserForTenant) {
AuthRecipeUserInfo authRecipeUserInfo = AuthRecipe.getUserById(tenantIdentifier.toAppIdentifier(),
storage, recipeUserId);
if (authRecipeUserInfo != null) {
if (!authRecipeUserInfo.tenantIds.contains(tenantIdentifier.getTenantId())) {
throw new UnauthorisedException("User is not part of requested tenant!");
}
}
}
}

String antiCsrfToken = enableAntiCsrf ? UUID.randomUUID().toString() : null;
Expand Down
1 change: 1 addition & 0 deletions src/main/java/io/supertokens/utils/SemVer.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public class SemVer implements Comparable<SemVer> {
public static final SemVer v5_0 = new SemVer("5.0");
public static final SemVer v5_1 = new SemVer("5.1");
public static final SemVer v5_2 = new SemVer("5.2");
public static final SemVer v5_3 = new SemVer("5.3");

final private String version;

Expand Down
6 changes: 4 additions & 2 deletions src/main/java/io/supertokens/webserver/WebserverAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
import io.supertokens.pluginInterface.Storage;
import io.supertokens.pluginInterface.emailpassword.exceptions.UnknownUserIdException;
import io.supertokens.pluginInterface.exceptions.StorageQueryException;
import io.supertokens.pluginInterface.multitenancy.*;
import io.supertokens.pluginInterface.multitenancy.AppIdentifier;
import io.supertokens.pluginInterface.multitenancy.TenantIdentifier;
import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException;
import io.supertokens.storageLayer.StorageLayer;
import io.supertokens.useridmapping.UserIdType;
Expand Down Expand Up @@ -77,10 +78,11 @@ public abstract class WebserverAPI extends HttpServlet {
supportedVersions.add(SemVer.v5_0);
supportedVersions.add(SemVer.v5_1);
supportedVersions.add(SemVer.v5_2);
supportedVersions.add(SemVer.v5_3);
}

public static SemVer getLatestCDIVersion() {
return SemVer.v5_2;
return SemVer.v5_3;
}

public SemVer getLatestCDIVersionForRequest(HttpServletRequest req)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,12 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I
}

AccessToken.VERSION accessTokenVersion = AccessToken.getAccessTokenVersionForCDI(version);
boolean shouldCheckUserForTenant = version.greaterThanOrEqualTo(SemVer.v5_3);

SessionInformationHolder sessionInfo = Session.createNewSession(
tenantIdentifier, storage, main, userId, userDataInJWT,
userDataInDatabase, enableAntiCsrf, accessTokenVersion,
useStaticSigningKey);
useStaticSigningKey, shouldCheckUserForTenant);

if (storage.getType() == STORAGE_TYPE.SQL) {
try {
Expand Down Expand Up @@ -143,6 +144,11 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I
super.sendJsonResponse(200, result, resp);
} catch (AccessTokenPayloadError e) {
throw new ServletException(new BadRequestException(e.getMessage()));
} catch (UnauthorisedException e) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

catching Unauthorised and returning a different status could get confusing. Create a new exception type for this.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

sure, okay

Copy link
Contributor Author

Choose a reason for hiding this comment

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

done

JsonObject reply = new JsonObject();
reply.addProperty("status", "USER_DOES_NOT_BELONG_TO_TENANT_ERROR");
reply.addProperty("message", e.getMessage());
super.sendJsonResponse(200, reply, resp);
} catch (NoSuchAlgorithmException | StorageQueryException | InvalidKeyException | InvalidKeySpecException |
StorageTransactionLogicException | SignatureException | IllegalBlockSizeException |
BadPaddingException | InvalidAlgorithmParameterException | NoSuchPaddingException |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ public void testSessionBehaviourWhenUserBelongsTo2TenantsAndThenLinkedToSomeOthe

AuthRecipe.createPrimaryUser(process.getProcess(), t1.toAppIdentifier(), t1Storage,
user2.getSupertokensUserId());
AuthRecipe.linkAccounts(process.getProcess(), t1.toAppIdentifier(), t1Storage, user1.getSupertokensUserId(),
AuthRecipe.linkAccounts(process.getProcess(), t2.toAppIdentifier(), t2Storage, user1.getSupertokensUserId(),
user2.getSupertokensUserId());

SessionInformationHolder session1 = Session.createNewSession(t2, t2Storage, process.getProcess(),
Expand Down
Loading
Loading