Skip to content
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
61 changes: 60 additions & 1 deletion src/main/java/io/supertokens/session/Session.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;
import java.util.UUID;

public class Session {
Expand Down Expand Up @@ -143,6 +144,43 @@ public static SessionInformationHolder regenerateToken(Main main, @Nonnull Strin
null);
}

@Deprecated
public static SessionInformationHolder regenerateTokenBeforeCDI2_21(Main main, @Nonnull String token,
@Nullable JsonObject userDataInJWT) throws StorageQueryException, StorageTransactionLogicException,
UnauthorisedException, InvalidKeySpecException, SignatureException, NoSuchAlgorithmException,
InvalidKeyException, UnsupportedEncodingException, JWT.JWTException, TryRefreshTokenException, UnsupportedJWTSigningAlgorithmException,
AccessTokenPayloadError {

// We assume the token has already been verified at this point. It may be expired or JWT signing key may have
// changed for it...
AccessTokenInfo accessToken = AccessToken.getInfoFromAccessTokenWithoutVerifying(token);

io.supertokens.pluginInterface.session.SessionInfo sessionInfo = getSession(main, accessToken.sessionHandle);
JsonObject newJWTUserPayload = userDataInJWT == null ? sessionInfo.userDataInJWT
: userDataInJWT;
updateSessionBeforeCDI2_21(main, accessToken.sessionHandle, null, newJWTUserPayload);

// if the above succeeds but the below fails, it's OK since the client will get server error and will try
// again. In this case, the JWT data will be updated again since the API will get the old JWT. In case there
// is a refresh call, the new JWT will get the new data.
if (accessToken.expiryTime < System.currentTimeMillis()) {
// in this case, we set the should not set the access token in the response since they will have to call
// the refresh API anyway.
return new SessionInformationHolder(
new SessionInfo(accessToken.sessionHandle, accessToken.userId, newJWTUserPayload), null, null, null,
null);
}

TokenInfo newAccessToken = AccessToken.createNewAccessToken(main, accessToken.sessionHandle, accessToken.userId,
accessToken.refreshTokenHash1, accessToken.parentRefreshTokenHash1, newJWTUserPayload,
accessToken.antiCsrfToken, accessToken.expiryTime, accessToken.version, sessionInfo.useStaticKey);

return new SessionInformationHolder(
new SessionInfo(accessToken.sessionHandle, accessToken.userId, newJWTUserPayload),
new TokenInfo(newAccessToken.token, newAccessToken.expiry, newAccessToken.createdTime), null, null,
null);
}

// pass antiCsrfToken to disable csrf check for this request
public static SessionInformationHolder getSession(Main main, @Nonnull String token, @Nullable String antiCsrfToken,
boolean enableAntiCsrf, Boolean doAntiCsrfCheck, boolean checkDatabase) throws StorageQueryException,
Expand Down Expand Up @@ -541,7 +579,28 @@ public static io.supertokens.pluginInterface.session.SessionInfo getSession(Main
}

public static void updateSession(Main main, String sessionHandle, @Nullable JsonObject sessionData,
@Nullable JsonObject jwtData) throws StorageQueryException, UnauthorisedException {
@Nullable JsonObject jwtData) throws StorageQueryException, UnauthorisedException, AccessTokenPayloadError {
if (jwtData != null && Arrays.stream(AccessTokenInfo.protectedPropNames).anyMatch(jwtData::has)) {
throw new AccessTokenPayloadError("The user payload contains protected field");
}

io.supertokens.pluginInterface.session.SessionInfo session = StorageLayer.getSessionStorage(main)
.getSession(sessionHandle);
// If there is no session, or session is expired
if (session == null || session.expiry <= System.currentTimeMillis()) {
throw new UnauthorisedException("Session does not exist.");
}

int numberOfRowsAffected = StorageLayer.getSessionStorage(main).updateSession(sessionHandle, sessionData, jwtData);
if (numberOfRowsAffected != 1) {
throw new UnauthorisedException("Session does not exist.");
}
}

@Deprecated
public static void updateSessionBeforeCDI2_21(Main main, String sessionHandle, @Nullable JsonObject sessionData,
@Nullable JsonObject jwtData) throws StorageQueryException, UnauthorisedException {

io.supertokens.pluginInterface.session.SessionInfo session = StorageLayer.getSessionStorage(main)
.getSession(sessionHandle);
// If there is no session, or session is expired
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ public static VERSION getAccessTokenVersion(AccessTokenInfo accessToken) {
}

public static class AccessTokenInfo {
static String[] protectedPropNames = {
public static String[] protectedPropNames = {
"sub",
"exp",
"iat",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import io.supertokens.Main;
import io.supertokens.exceptions.AccessTokenPayloadError;
import io.supertokens.exceptions.UnauthorisedException;
import io.supertokens.output.Logging;
import io.supertokens.pluginInterface.RECIPE_ID;
import io.supertokens.pluginInterface.exceptions.StorageQueryException;
import io.supertokens.session.Session;
import io.supertokens.utils.SemVer;
import io.supertokens.utils.Utils;
import io.supertokens.webserver.InputParser;
import io.supertokens.webserver.WebserverAPI;
Expand Down Expand Up @@ -56,7 +58,11 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO
assert userDataInJWT != null;

try {
Session.updateSession(main, sessionHandle, null, userDataInJWT);
if (getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v2_21)) {
Session.updateSession(main, sessionHandle, null, userDataInJWT);
} else {
Session.updateSessionBeforeCDI2_21(main, sessionHandle, null, userDataInJWT);
}

JsonObject result = new JsonObject();

Expand All @@ -65,6 +71,8 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO

} catch (StorageQueryException e) {
throw new ServletException(e);
} catch(AccessTokenPayloadError e) {
throw new ServletException(new BadRequestException(e.getMessage()));
} catch (UnauthorisedException e) {
Logging.debug(main, Utils.exceptionStacktraceToString(e));
JsonObject reply = new JsonObject();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@

import com.google.gson.JsonObject;
import io.supertokens.Main;
import io.supertokens.exceptions.AccessTokenPayloadError;
import io.supertokens.exceptions.UnauthorisedException;
import io.supertokens.output.Logging;
import io.supertokens.pluginInterface.RECIPE_ID;
import io.supertokens.pluginInterface.exceptions.StorageQueryException;
import io.supertokens.session.Session;
import io.supertokens.utils.SemVer;
import io.supertokens.utils.Utils;
import io.supertokens.webserver.InputParser;
import io.supertokens.webserver.WebserverAPI;
Expand Down Expand Up @@ -78,14 +80,21 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO
assert userDataInDatabase != null;

try {
Session.updateSession(main, sessionHandle, userDataInDatabase, null);
// This is only here for consistency: the difference between the two versions is the handling of jwtData which is always null here
if (getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v2_21)) {
Session.updateSession(main, sessionHandle, userDataInDatabase, null);
} else {
Session.updateSessionBeforeCDI2_21(main, sessionHandle, userDataInDatabase, null);
}

JsonObject result = new JsonObject();
result.addProperty("status", "OK");
super.sendJsonResponse(200, result, resp);

} catch (StorageQueryException e) {
throw new ServletException(e);
} catch(AccessTokenPayloadError e) {
throw new ServletException(new BadRequestException(e.getMessage()));
} catch (UnauthorisedException e) {
Logging.debug(main, Utils.exceptionStacktraceToString(e));
JsonObject reply = new JsonObject();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import io.supertokens.session.Session;
import io.supertokens.session.info.SessionInformationHolder;
import io.supertokens.session.jwt.JWT;
import io.supertokens.utils.SemVer;
import io.supertokens.utils.Utils;
import io.supertokens.webserver.InputParser;
import io.supertokens.webserver.WebserverAPI;
Expand All @@ -43,6 +44,7 @@
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.Arrays;

public class SessionRegenerateAPI extends WebserverAPI {

Expand All @@ -67,7 +69,9 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I
JsonObject userDataInJWT = InputParser.parseJsonObjectOrThrowError(input, "userDataInJWT", true);

try {
SessionInformationHolder sessionInfo = Session.regenerateToken(main, accessToken, userDataInJWT);
SessionInformationHolder sessionInfo = getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v2_21) ?
Session.regenerateToken(main, accessToken, userDataInJWT) :
Session.regenerateTokenBeforeCDI2_21(main, accessToken, userDataInJWT);

JsonObject result = sessionInfo.toJsonObject();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,7 @@ public void updateSessionInfo() throws Exception {
// * Try getting and updating session information for a non-existent session handle -> Verify that both throw
// * UnauthorisedException for session not existing
@Test
public void gettingAndUpdatingSessionDataForNonExistentSession()
throws InterruptedException, StorageQueryException {
public void gettingAndUpdatingSessionDataForNonExistentSession() throws Exception {

String[] args = { "../" };
TestingProcessManager.TestingProcess process = TestingProcessManager.start(args);
Expand Down
3 changes: 1 addition & 2 deletions src/test/java/io/supertokens/test/session/SessionTest4.java
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,7 @@ public void checkForNumberOfDeletedSessions() throws Exception {
}

@Test
public void gettingAndUpdatingSessionDataForNonExistantSession()
throws InterruptedException, StorageQueryException {
public void gettingAndUpdatingSessionDataForNonExistantSession() throws Exception {

String[] args = { "../" };
TestingProcessManager.TestingProcess process = TestingProcessManager.start(args);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

import static org.junit.Assert.*;

public class HandshakeAPITest2_19 {
public class HandshakeAPITest2_21 {
@Rule
public TestRule watchman = Utils.getOnFailure();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Copyright (c) 2021, 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.test.session.api;

import com.google.gson.JsonObject;
import io.supertokens.ProcessState;
import io.supertokens.test.TestingProcessManager;
import io.supertokens.test.Utils;
import io.supertokens.test.httpRequest.HttpRequestForTesting;
import io.supertokens.test.httpRequest.HttpResponseException;
import io.supertokens.utils.SemVer;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;

import java.util.HashMap;

import static org.junit.Assert.*;

public class JWTDataAPITest2_21 {

@Rule
public TestRule watchman = Utils.getOnFailure();

@AfterClass
public static void afterTesting() {
Utils.afterTesting();
}

@Before
public void beforeEach() {
Utils.reset();
}

@Test
public void testThatAddingProtectedPropsThrow() throws Exception {
String[] args = { "../" };

TestingProcessManager.TestingProcess process = TestingProcessManager.start(args);
assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED));

// createSession with JWT payload
String userId = "userId";
JsonObject userDataInJWT = new JsonObject();
userDataInJWT.addProperty("key", "value");
JsonObject userDataInDatabase = new JsonObject();
userDataInDatabase.addProperty("key", "value");

JsonObject request = new JsonObject();
request.addProperty("userId", userId);
request.add("userDataInJWT", userDataInJWT);
request.add("userDataInDatabase", userDataInDatabase);
request.addProperty("enableAntiCsrf", false);

JsonObject sessionInfo = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "",
"http://localhost:3567/recipe/session", request, 1000, 1000, null, SemVer.v2_21.get(),
"session");
assertEquals(sessionInfo.get("status").getAsString(), "OK");
String sessionHandle = sessionInfo.get("session").getAsJsonObject().get("handle").getAsString();


// change JWT payload using API
JsonObject newUserDataInJwt = new JsonObject();
newUserDataInJwt.addProperty("sub", "value2");
request = new JsonObject();
request.addProperty("sessionHandle", sessionHandle);
request.add("userDataInJWT", newUserDataInJwt);
try {
HttpRequestForTesting.sendJsonPUTRequest(process.getProcess(), "",
"http://localhost:3567/recipe/jwt/data", request, 1000, 1000, null, SemVer.v2_21.get(),
"session");
fail();
} catch (HttpResponseException e) {
assertEquals(e.statusCode, 400);
assertEquals(e.getMessage(),
"Http error. Status Code: 400. Message: The user payload contains protected field");
}

process.kill();
assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED));

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import io.supertokens.test.TestingProcessManager;
import io.supertokens.test.Utils;
import io.supertokens.test.httpRequest.HttpRequestForTesting;
import io.supertokens.test.httpRequest.HttpResponseException;
import io.supertokens.utils.SemVer;
import org.junit.*;
import org.junit.rules.TestRule;
Expand All @@ -32,7 +31,7 @@
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

public class RefreshSessionAPITest2_19 {
public class RefreshSessionAPITest2_21 {
@Rule
public TestRule watchman = Utils.getOnFailure();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,17 @@ public void testCallRegenerateAPIWithProtectedFieldInJWTV3Token() throws Excepti
assertEquals(caught.statusCode, 400);
assertEquals(caught.getMessage(), "Http error. Status Code: 400. Message:" + " The user payload contains protected field");

JsonObject sessionRefreshBody = new JsonObject();

sessionRefreshBody.addProperty("refreshToken",
sessionInfo.get("refreshToken").getAsJsonObject().get("token").getAsString());
sessionRefreshBody.addProperty("enableAntiCsrf", false);

JsonObject sessionRefreshResponse = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "",
"http://localhost:3567/recipe/session/refresh", sessionRefreshBody, 1000, 1000, null,
Utils.getCdiVersionStringLatestForTests(), "session");

assertEquals("OK", sessionRefreshResponse.get("status").getAsString());
process.kill();
assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED));
}
Expand Down