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 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]


## [9.4.0]

- 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
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.4.0"


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"
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright (c) 2024, VRAI Labs and/or its affiliates. All rights reserved.
*
* This software is licensed under the Apache License, Version 2.0 (the
* "License") as published by the Apache Software Foundation.
*
* You may not use this file except in compliance with the License. You may
* obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package io.supertokens.exceptions;

public class UserNotInTenantException extends Exception {

public UserNotInTenantException(String err) {
super(err);
}

}
34 changes: 22 additions & 12 deletions src/main/java/io/supertokens/session/Session.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,10 @@
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;
import io.supertokens.exceptions.TokenTheftDetectedException;
import io.supertokens.exceptions.TryRefreshTokenException;
import io.supertokens.exceptions.UnauthorisedException;
import io.supertokens.exceptions.*;
import io.supertokens.jwt.exceptions.UnsupportedJWTSigningAlgorithmException;
import io.supertokens.multitenancy.Multitenancy;
import io.supertokens.pluginInterface.STORAGE_TYPE;
Expand Down Expand Up @@ -78,11 +76,11 @@ public static SessionInformationHolder createNewSession(TenantIdentifier tenantI
@Nonnull JsonObject userDataInDatabase)
throws NoSuchAlgorithmException, StorageQueryException, InvalidKeyException,
InvalidKeySpecException, StorageTransactionLogicException, SignatureException, IllegalBlockSizeException,
BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException, UnauthorisedException,
BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException, UserNotInTenantException,
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 +99,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 | UserNotInTenantException e) {
throw new IllegalStateException(e);
}
}
Expand All @@ -121,8 +120,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 | UserNotInTenantException e) {
throw new IllegalStateException(e);
}
}
Expand All @@ -132,11 +131,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, UserNotInTenantException {
String sessionHandle = UUID.randomUUID().toString();
if (!tenantIdentifier.getTenantId().equals(TenantIdentifier.DEFAULT_TENANT_ID)) {
sessionHandle += "_" + tenantIdentifier.getTenantId();
Expand All @@ -151,6 +150,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 +166,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 UserNotInTenantException("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 @@ -23,6 +23,7 @@
import io.supertokens.config.Config;
import io.supertokens.exceptions.AccessTokenPayloadError;
import io.supertokens.exceptions.UnauthorisedException;
import io.supertokens.exceptions.UserNotInTenantException;
import io.supertokens.jwt.exceptions.UnsupportedJWTSigningAlgorithmException;
import io.supertokens.output.Logging;
import io.supertokens.pluginInterface.RECIPE_ID;
Expand Down Expand Up @@ -99,11 +100,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 +145,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 (UserNotInTenantException e) {
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