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

refactor: Replace TOTP_NOT_ENABLED_ERROR status and make deviceName optional #729

Merged
merged 20 commits into from
Sep 28, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
06b2cf3
refactor: Dont send TOTP_NOT_ENABLED_ERROR status
KShivendu Jun 22, 2023
693b70e
refactor: Add comments
KShivendu Jun 23, 2023
b10a23c
chores: Remove extra comments
KShivendu Jun 23, 2023
1a14e22
Merge branch 'feat/mfa' into refactor/avoid-totp-not-enabled
KShivendu Jun 26, 2023
14209d8
refactor: Completely replace totp not enabled error with unknown devi…
KShivendu Jun 27, 2023
157d94a
refactor: Remove Totp not enabled error
KShivendu Jun 27, 2023
fc9f706
feat: Make device name optional and generate it from number of existi…
KShivendu Jun 27, 2023
ec6dd7e
Replace TotpNotEnabledError with UnknownUserIdTotpError
KShivendu Jun 28, 2023
98b24ae
refactor: Recursively generate device name when it already exists
KShivendu Jun 29, 2023
646b0b8
refactor: Remove redundant arguments
KShivendu Jun 29, 2023
430704e
feat: Remove the param to allow unverified devices from the verify to…
KShivendu Jul 3, 2023
a7d2f27
Merge branch 'master' into refactor/avoid-totp-not-enabled
KShivendu Sep 27, 2023
363492c
feat: Reject unverified devices
KShivendu Sep 27, 2023
5b68216
Merge branch 'feat/mfa' into refactor/avoid-totp-not-enabled
KShivendu Sep 27, 2023
59373c2
feat: Add UNKNOWN_USER_ID_ERROR to verify totp api
KShivendu Sep 27, 2023
84b1b9d
feat: Throw Unknown user id error when device gets deleted during ver…
KShivendu Sep 27, 2023
7ef46d1
Merge branch 'feat/mfa' into refactor/avoid-totp-not-enabled
sattvikc Sep 28, 2023
29f9643
fix: core fixes
sattvikc Sep 28, 2023
6be5b8c
fix: cleanup
sattvikc Sep 28, 2023
0139624
fix: tests
sattvikc Sep 28, 2023
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
9 changes: 4 additions & 5 deletions src/main/java/io/supertokens/inmemorydb/Start.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@
import io.supertokens.pluginInterface.totp.TOTPStorage;
import io.supertokens.pluginInterface.totp.TOTPUsedCode;
import io.supertokens.pluginInterface.totp.exception.DeviceAlreadyExistsException;
import io.supertokens.pluginInterface.totp.exception.TotpNotEnabledException;
import io.supertokens.pluginInterface.totp.exception.UnknownDeviceException;
import io.supertokens.pluginInterface.totp.exception.UsedCodeAlreadyExistsException;
import io.supertokens.pluginInterface.totp.sqlStorage.TOTPSQLStorage;
Expand Down Expand Up @@ -1257,7 +1256,7 @@ public int countUsersEnabledTotpAndActiveSince(AppIdentifier appIdentifier, long
throw new StorageQueryException(e);
}
}

@Override
public int countUsersEnabledMfa(AppIdentifier appIdentifier) throws StorageQueryException {
try {
Expand All @@ -1266,7 +1265,7 @@ public int countUsersEnabledMfa(AppIdentifier appIdentifier) throws StorageQuery
throw new StorageQueryException(e);
}
}

@Override
public int countUsersEnabledMfaAndActiveSince(AppIdentifier appIdentifier, long time)
throws StorageQueryException {
Expand Down Expand Up @@ -2673,7 +2672,7 @@ public TOTPDevice[] getDevices_Transaction(TransactionConnection con, AppIdentif
@Override
public void insertUsedCode_Transaction(TransactionConnection con, TenantIdentifier tenantIdentifier,
TOTPUsedCode usedCodeObj)
throws StorageQueryException, TotpNotEnabledException, UsedCodeAlreadyExistsException,
throws StorageQueryException, UnknownDeviceException, UsedCodeAlreadyExistsException,
TenantOrAppNotFoundException {
Connection sqlCon = (Connection) con.getConnection();
try {
Expand All @@ -2687,7 +2686,7 @@ public void insertUsedCode_Transaction(TransactionConnection con, TenantIdentifi
Config.getConfig(this).getTotpUsersTable(),
new String[]{"app_id", "user_id"},
Copy link
Contributor

Choose a reason for hiding this comment

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

see my comment in plugin interface PR

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I believe you're talking about replacing TotpNotEnabledError with new UnknownUserIdError. If yes, done.

Copy link
Contributor

Choose a reason for hiding this comment

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

Please check and confirm.

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

new Object[]{tenantIdentifier.getAppId(), usedCodeObj.userId})) {
throw new TotpNotEnabledException();
throw new UnknownDeviceException();

} else if (isForeignKeyConstraintError(
e.getMessage(),
Expand Down
78 changes: 36 additions & 42 deletions src/main/java/io/supertokens/totp/Totp.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import io.supertokens.pluginInterface.totp.TOTPDevice;
import io.supertokens.pluginInterface.totp.TOTPUsedCode;
import io.supertokens.pluginInterface.totp.exception.DeviceAlreadyExistsException;
import io.supertokens.pluginInterface.totp.exception.TotpNotEnabledException;
import io.supertokens.pluginInterface.totp.exception.UnknownDeviceException;
import io.supertokens.pluginInterface.totp.exception.UsedCodeAlreadyExistsException;
import io.supertokens.pluginInterface.totp.sqlStorage.TOTPSQLStorage;
Expand Down Expand Up @@ -107,6 +106,11 @@ public static TOTPDevice registerDevice(AppIdentifierWithStorage appIdentifierWi
}

TOTPSQLStorage totpStorage = appIdentifierWithStorage.getTOTPStorage();

if (deviceName == null) {
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
TOTPDevice[] devices = totpStorage.getDevices(appIdentifierWithStorage, userId);
deviceName = "TOTP Device " + (devices.length + 1);
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
}

String secret = generateSecret();
TOTPDevice device = new TOTPDevice(userId, deviceName, secret, period, skew, false);
Expand All @@ -118,7 +122,7 @@ public static TOTPDevice registerDevice(AppIdentifierWithStorage appIdentifierWi
private static void checkAndStoreCode(TenantIdentifierWithStorage tenantIdentifierWithStorage, Main main,
String userId, TOTPDevice[] devices,
String code)
throws InvalidTotpException, TotpNotEnabledException,
throws InvalidTotpException, UnknownDeviceException,
LimitReachedException, StorageQueryException, StorageTransactionLogicException,
TenantOrAppNotFoundException {
// Note that the TOTP cron runs every 1 hour, so all the expired tokens can stay
Expand Down Expand Up @@ -241,7 +245,7 @@ private static void checkAndStoreCode(TenantIdentifierWithStorage tenantIdentifi
try {
totpSQLStorage.insertUsedCode_Transaction(con, tenantIdentifierWithStorage, newCode);
totpSQLStorage.commitTransaction(con);
} catch (UsedCodeAlreadyExistsException | TotpNotEnabledException e) {
} catch (UsedCodeAlreadyExistsException | UnknownDeviceException e) {
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
throw new StorageTransactionLogicException(e);
}

Expand All @@ -264,8 +268,8 @@ private static void checkAndStoreCode(TenantIdentifierWithStorage tenantIdentifi
throw (LimitReachedException) e.actualException;
} else if (e.actualException instanceof InvalidTotpException) {
throw (InvalidTotpException) e.actualException;
} else if (e.actualException instanceof TotpNotEnabledException) {
throw (TotpNotEnabledException) e.actualException;
} else if (e.actualException instanceof UnknownDeviceException) {
throw (UnknownDeviceException) e.actualException;
} else if (e.actualException instanceof UsedCodeAlreadyExistsException) {
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
// retry the transaction after a small delay:
int delayInMs = (int) (Math.random() * 10 + 1);
Expand All @@ -284,7 +288,7 @@ private static void checkAndStoreCode(TenantIdentifierWithStorage tenantIdentifi
@TestOnly
public static boolean verifyDevice(Main main,
String userId, String deviceName, String code)
throws TotpNotEnabledException, UnknownDeviceException, InvalidTotpException,
throws UnknownDeviceException, InvalidTotpException,
LimitReachedException, StorageQueryException, StorageTransactionLogicException {
try {
return verifyDevice(new TenantIdentifierWithStorage(null, null, null, StorageLayer.getStorage(main)), main,
Expand All @@ -296,7 +300,7 @@ public static boolean verifyDevice(Main main,

public static boolean verifyDevice(TenantIdentifierWithStorage tenantIdentifierWithStorage, Main main,
String userId, String deviceName, String code)
throws TotpNotEnabledException, UnknownDeviceException, InvalidTotpException,
throws UnknownDeviceException, InvalidTotpException,
LimitReachedException, StorageQueryException, StorageTransactionLogicException,
TenantOrAppNotFoundException {
// Here boolean return value tells whether the device has been
Expand All @@ -312,7 +316,7 @@ public static boolean verifyDevice(TenantIdentifierWithStorage tenantIdentifierW
// Check if the user has any devices:
TOTPDevice[] devices = totpStorage.getDevices(tenantIdentifierWithStorage.toAppIdentifier(), userId);
if (devices.length == 0) {
throw new TotpNotEnabledException();
throw new UnknownDeviceException();
}

// Check if the requested device exists:
Expand All @@ -337,8 +341,12 @@ public static boolean verifyDevice(TenantIdentifierWithStorage tenantIdentifierW
// verified in the devices table (because it was deleted/renamed). So the user
// gets a UnknownDevceException.
// This behaviour is okay so we can ignore it.
checkAndStoreCode(tenantIdentifierWithStorage, main, userId, new TOTPDevice[]{matchingDevice},
code);
try{
checkAndStoreCode(tenantIdentifierWithStorage, main, userId, new TOTPDevice[]{matchingDevice}, code);
} catch (UnknownDeviceException e) {
// User must have deleted the device in parallel.
throw new UnknownDeviceException();
}
// Will reach here only if the code is valid:
totpStorage.markDeviceAsVerified(tenantIdentifierWithStorage.toAppIdentifier(), userId, deviceName);
return true; // Newly verified
Expand All @@ -347,7 +355,7 @@ public static boolean verifyDevice(TenantIdentifierWithStorage tenantIdentifierW
@TestOnly
public static void verifyCode(Main main, String userId,
String code, boolean allowUnverifiedDevices)
throws TotpNotEnabledException, InvalidTotpException, LimitReachedException,
throws InvalidTotpException, LimitReachedException,
StorageQueryException, StorageTransactionLogicException, FeatureNotEnabledException {
try {
verifyCode(new TenantIdentifierWithStorage(null, null, null, StorageLayer.getStorage(main)), main,
Expand All @@ -359,7 +367,7 @@ public static void verifyCode(Main main, String userId,

public static void verifyCode(TenantIdentifierWithStorage tenantIdentifierWithStorage, Main main, String userId,
String code, boolean allowUnverifiedDevices)
throws TotpNotEnabledException, InvalidTotpException, LimitReachedException,
throws InvalidTotpException, LimitReachedException,
StorageQueryException, StorageTransactionLogicException, FeatureNotEnabledException,
TenantOrAppNotFoundException {

Expand All @@ -374,7 +382,8 @@ public static void verifyCode(TenantIdentifierWithStorage tenantIdentifierWithSt
// Check if the user has any devices:
TOTPDevice[] devices = totpStorage.getDevices(tenantIdentifierWithStorage.toAppIdentifier(), userId);
if (devices.length == 0) {
throw new TotpNotEnabledException();
// No devices found. So we can't verify the code anyway.
throw new InvalidTotpException();
Copy link
Contributor

Choose a reason for hiding this comment

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

maybe it's better to throw an UnknownUserIdTotpException, since the input to this API is also the userId

Copy link
Contributor

Choose a reason for hiding this comment

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

This would be an additional status code that is sent to the backend sdk

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

}

// Filter out unverified devices:
Expand All @@ -386,13 +395,19 @@ public static void verifyCode(TenantIdentifierWithStorage tenantIdentifierWithSt
// another API call. We will still check the code against the updated set of
// devices and store it in the used codes table. This behaviour is okay so we
// can ignore it.
checkAndStoreCode(tenantIdentifierWithStorage, main, userId, devices, code);
try{
checkAndStoreCode(tenantIdentifierWithStorage, main, userId, devices, code);
} catch (UnknownDeviceException e) {
// User must have deleted the device in parallel
// since they cannot un-verify a device (no API exists)
throw new InvalidTotpException();
Copy link
Contributor

Choose a reason for hiding this comment

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

maybe it's better to throw an UnknownUserIdTotpException, since the input to this API is also the userId

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

}
}

@TestOnly
public static void removeDevice(Main main, String userId,
String deviceName)
throws StorageQueryException, UnknownDeviceException, TotpNotEnabledException,
throws StorageQueryException, UnknownDeviceException,
StorageTransactionLogicException {
try {
removeDevice(new AppIdentifierWithStorage(null, null, StorageLayer.getStorage(main)),
Expand All @@ -407,7 +422,7 @@ public static void removeDevice(Main main, String userId,
*/
public static void removeDevice(AppIdentifierWithStorage appIdentifierWithStorage, String userId,
String deviceName)
throws StorageQueryException, UnknownDeviceException, TotpNotEnabledException,
throws StorageQueryException, UnknownDeviceException,
StorageTransactionLogicException, TenantOrAppNotFoundException {
TOTPSQLStorage storage = appIdentifierWithStorage.getTOTPStorage();

Expand All @@ -432,12 +447,6 @@ public static void removeDevice(AppIdentifierWithStorage appIdentifierWithStorag
return;
} catch (StorageTransactionLogicException e) {
if (e.actualException instanceof UnknownDeviceException) {
// Check if any device exists for the user:
TOTPDevice[] devices = storage.getDevices(appIdentifierWithStorage, userId);
if (devices.length == 0) {
throw new TotpNotEnabledException();
}

throw (UnknownDeviceException) e.actualException;
}

Expand All @@ -448,8 +457,7 @@ public static void removeDevice(AppIdentifierWithStorage appIdentifierWithStorag
@TestOnly
public static void updateDeviceName(Main main, String userId,
String oldDeviceName, String newDeviceName)
throws StorageQueryException, DeviceAlreadyExistsException, UnknownDeviceException,
TotpNotEnabledException {
throws StorageQueryException, DeviceAlreadyExistsException, UnknownDeviceException {
try {
updateDeviceName(new AppIdentifierWithStorage(null, null, StorageLayer.getStorage(main)),
userId, oldDeviceName, newDeviceName);
Expand All @@ -460,25 +468,14 @@ public static void updateDeviceName(Main main, String userId,

public static void updateDeviceName(AppIdentifierWithStorage appIdentifierWithStorage, String userId,
String oldDeviceName, String newDeviceName)
throws StorageQueryException, DeviceAlreadyExistsException, UnknownDeviceException,
TotpNotEnabledException, TenantOrAppNotFoundException {
throws StorageQueryException, DeviceAlreadyExistsException, UnknownDeviceException, TenantOrAppNotFoundException {
TOTPSQLStorage totpStorage = appIdentifierWithStorage.getTOTPStorage();
try {
totpStorage.updateDeviceName(appIdentifierWithStorage, userId, oldDeviceName, newDeviceName);
} catch (UnknownDeviceException e) {
// Check if any device exists for the user:
TOTPDevice[] devices = totpStorage.getDevices(appIdentifierWithStorage, userId);
if (devices.length == 0) {
throw new TotpNotEnabledException();
} else {
throw e;
}
}
totpStorage.updateDeviceName(appIdentifierWithStorage, userId, oldDeviceName, newDeviceName);
}

@TestOnly
public static TOTPDevice[] getDevices(Main main, String userId)
throws StorageQueryException, TotpNotEnabledException {
throws StorageQueryException {
try {
return getDevices(new AppIdentifierWithStorage(null, null, StorageLayer.getStorage(main)),
userId);
Expand All @@ -488,13 +485,10 @@ public static TOTPDevice[] getDevices(Main main, String userId)
}

public static TOTPDevice[] getDevices(AppIdentifierWithStorage appIdentifierWithStorage, String userId)
throws StorageQueryException, TotpNotEnabledException, TenantOrAppNotFoundException {
throws StorageQueryException, TenantOrAppNotFoundException {
TOTPSQLStorage totpStorage = appIdentifierWithStorage.getTOTPStorage();

TOTPDevice[] devices = totpStorage.getDevices(appIdentifierWithStorage, userId);
if (devices.length == 0) {
throw new TotpNotEnabledException();
}
return devices;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException;
import io.supertokens.pluginInterface.totp.TOTPDevice;
import io.supertokens.pluginInterface.totp.exception.DeviceAlreadyExistsException;
import io.supertokens.pluginInterface.totp.exception.TotpNotEnabledException;
import io.supertokens.pluginInterface.totp.exception.UnknownDeviceException;
import io.supertokens.totp.Totp;
import io.supertokens.useridmapping.UserIdType;
Expand Down Expand Up @@ -42,7 +41,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I
JsonObject input = InputParser.parseJsonObjectOrThrowError(req);

String userId = InputParser.parseStringOrThrowError(input, "userId", false);
String deviceName = InputParser.parseStringOrThrowError(input, "deviceName", false);
String deviceName = InputParser.parseStringOrThrowError(input, "deviceName", true);
Integer skew = InputParser.parseIntOrThrowError(input, "skew", false);
Integer period = InputParser.parseIntOrThrowError(input, "period", false);

Expand All @@ -52,7 +51,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I
if (userId.isEmpty()) {
throw new ServletException(new BadRequestException("userId cannot be empty"));
}
if (deviceName.isEmpty()) {
if (deviceName != null && deviceName.isEmpty()) {
// Only Null or valid device name are allowed
throw new ServletException(new BadRequestException("deviceName cannot be empty"));
}
if (skew < 0) {
Expand Down Expand Up @@ -87,6 +87,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I
TOTPDevice device = Totp.registerDevice(appIdentifierWithStorage, main, userId, deviceName, skew, period);

result.addProperty("status", "OK");
result.addProperty("deviceName", device.deviceName);
result.addProperty("secret", device.secretKey);
super.sendJsonResponse(200, result, resp);
} catch (DeviceAlreadyExistsException e) {
Expand Down Expand Up @@ -143,9 +144,6 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO

result.addProperty("status", "OK");
super.sendJsonResponse(200, result, resp);
} catch (TotpNotEnabledException e) {
result.addProperty("status", "TOTP_NOT_ENABLED_ERROR");
super.sendJsonResponse(200, result, resp);
} catch (UnknownDeviceException e) {
result.addProperty("status", "UNKNOWN_DEVICE_ERROR");
super.sendJsonResponse(200, result, resp);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import io.supertokens.pluginInterface.multitenancy.AppIdentifierWithStorage;
import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException;
import io.supertokens.pluginInterface.totp.TOTPDevice;
import io.supertokens.pluginInterface.totp.exception.TotpNotEnabledException;
import io.supertokens.totp.Totp;
import io.supertokens.useridmapping.UserIdType;
import io.supertokens.webserver.InputParser;
Expand Down Expand Up @@ -80,9 +79,6 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO
result.addProperty("status", "OK");
result.add("devices", devicesArray);
super.sendJsonResponse(200, result, resp);
} catch (TotpNotEnabledException e) {
result.addProperty("status", "TOTP_NOT_ENABLED_ERROR");
super.sendJsonResponse(200, result, resp);
} catch (StorageQueryException | TenantOrAppNotFoundException e) {
throw new ServletException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import io.supertokens.pluginInterface.exceptions.StorageTransactionLogicException;
import io.supertokens.pluginInterface.multitenancy.AppIdentifierWithStorage;
import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException;
import io.supertokens.pluginInterface.totp.exception.TotpNotEnabledException;
import io.supertokens.pluginInterface.totp.exception.UnknownDeviceException;
import io.supertokens.totp.Totp;
import io.supertokens.useridmapping.UserIdType;
Expand Down Expand Up @@ -75,9 +74,6 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I
result.addProperty("status", "OK");
result.addProperty("didDeviceExist", true);
super.sendJsonResponse(200, result, resp);
} catch (TotpNotEnabledException e) {
result.addProperty("status", "TOTP_NOT_ENABLED_ERROR");
super.sendJsonResponse(200, result, resp);
} catch (UnknownDeviceException e) {
result.addProperty("status", "OK");
result.addProperty("didDeviceExist", false);
Expand Down
Loading