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

feat: Implement TOTP inmemory classes #564

Merged
merged 45 commits into from
Mar 27, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
06cf6d5
feat: Implement TOTP inmemory classes
KShivendu Feb 10, 2023
37aec0e
feat: Create tables and indexes for TOTP
KShivendu Feb 10, 2023
dcbaf29
refactor: Remove comments and unused code
KShivendu Feb 10, 2023
81e3765
feat: Throws expected exceptions from totp in memory implementation w…
KShivendu Feb 13, 2023
7251944
feat: Fix TOTP.java and inmemory implementation
KShivendu Feb 16, 2023
d5551b6
feat: Improvemnts in TOTP in memory implementation
KShivendu Feb 16, 2023
3530939
feat: Improve tests and used code handling logic
KShivendu Feb 17, 2023
0f10e8b
feat: Improve TOTP inmemorydb queries
KShivendu Feb 17, 2023
074ddfc
refactor: Use compound foreign key in totp_used_codes table and fix o…
KShivendu Feb 20, 2023
dc3b143
fix: Remove related used codes when a user device is being deleted
KShivendu Feb 20, 2023
ed44812
feat(totp): Add cron to remove expired codes and improve tests
KShivendu Feb 20, 2023
957e016
feat: Add java-otp as a dependency
KShivendu Feb 21, 2023
22e64a5
feat: Introduce totp_users to keep track of users who have more than …
KShivendu Feb 21, 2023
fe17057
test: Use equals function for cleaner code
KShivendu Feb 21, 2023
6106c1a
feat: Improve TOTP recipe
KShivendu Feb 22, 2023
c26ae12
feat: Improve TOTP recipe
KShivendu Feb 23, 2023
457f091
refactor: Remove device_name from totp_used_codes table
KShivendu Feb 23, 2023
6fbfebc
feat: Improve TOTP recipe
KShivendu Feb 27, 2023
a83c6f6
feat: Improve TOTP recipe
KShivendu Feb 28, 2023
54ad75e
feat: Improve TOTP rate limiting
KShivendu Feb 28, 2023
4ac4760
refactor: Remove redundant method deleteAllTotpDataForUser
KShivendu Feb 28, 2023
2075131
feat: Add APIs for TOTP recipe
KShivendu Mar 1, 2023
25ea1b5
feat: Improve TOTP recipe
KShivendu Mar 2, 2023
3aca9e4
refactor: Remove created_time index from totp_used_codes table
KShivendu Mar 2, 2023
56025f1
Merge branch '4.4' into feat/totp-inmemory
KShivendu Mar 2, 2023
cf16b6c
refactor: Remove foreign key constraint emulation in TOTP
KShivendu Mar 2, 2023
8c18d03
feat: Improve TOTP recipe
KShivendu Mar 7, 2023
6d8a2b2
feat: Improve TOTP recipe
KShivendu Mar 9, 2023
39ff5b7
feat: Improve TOTP implementation
KShivendu Mar 10, 2023
3adc73d
refactor: Adjust order of columns in totp_used_codes table
KShivendu Mar 10, 2023
3fe112f
Merge branch '4.4' into feat/totp-inmemory
rishabhpoddar Mar 12, 2023
35b06a0
feat: Improve TOTP implementation
KShivendu Mar 14, 2023
c33fb26
test: Add API layer test for TOTP recipe
KShivendu Mar 15, 2023
235335f
feat: Finish totp implementation
KShivendu Mar 16, 2023
04e4fd7
refactor: Update TOTP recipe vars and comments
KShivendu Mar 20, 2023
5ab015e
chores: Mention API and DB changes for TOTP recipe in CHANGELOG
KShivendu Mar 20, 2023
e6844bf
Merge branch '4.4' into feat/totp-inmemory
KShivendu Mar 20, 2023
4e13470
feat: Add support for active users stats (#585)
KShivendu Mar 21, 2023
b02a420
test: Add tests for active users update across different API calls (#…
KShivendu Mar 22, 2023
5b2740e
feat: Make TOTP a paid feature and report stats (#589)
KShivendu Mar 23, 2023
9aa9496
feat: Check TOTP feature flag in TOTP recipe functions (#592)
KShivendu Mar 23, 2023
d46fe69
updates CDI version info
jscyo Mar 24, 2023
00ccbe6
test: Fix failing tests (#598)
KShivendu Mar 27, 2023
f63a462
feat: Add new API and tests for counting active users (#596)
KShivendu Mar 27, 2023
90c9af1
fixes tests and review comments
rishabhpoddar Mar 27, 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
4 changes: 4 additions & 0 deletions src/main/java/io/supertokens/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import io.supertokens.cronjobs.deleteExpiredPasswordResetTokens.DeleteExpiredPasswordResetTokens;
import io.supertokens.cronjobs.deleteExpiredPasswordlessDevices.DeleteExpiredPasswordlessDevices;
import io.supertokens.cronjobs.deleteExpiredSessions.DeleteExpiredSessions;
import io.supertokens.cronjobs.deleteExpiredTotpTokens.DeleteExpiredTotpTokens;
import io.supertokens.cronjobs.telemetry.Telemetry;
import io.supertokens.emailpassword.PasswordHashing;
import io.supertokens.exceptions.QuitProgramException;
Expand Down Expand Up @@ -204,6 +205,9 @@ private void init() throws IOException {
// removes passwordless devices with only expired codes
Cronjobs.addCronjob(this, DeleteExpiredPasswordlessDevices.getInstance(this));

// removes expired TOTP used tokens
Cronjobs.addCronjob(this, DeleteExpiredTotpTokens.getInstance(this));

// starts Telemetry cronjob if the user has not disabled it
if (!Config.getConfig(this).isTelemetryDisabled()) {
Cronjobs.addCronjob(this, Telemetry.getInstance(this));
Expand Down
1 change: 1 addition & 0 deletions src/main/java/io/supertokens/authRecipe/AuthRecipe.java
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ private static void deleteNonAuthRecipeUser(Main main, String userId) throws Sto
StorageLayer.getSessionStorage(main).deleteSessionsOfUser(userId);
StorageLayer.getEmailVerificationStorage(main).deleteEmailVerificationUserInfo(userId);
StorageLayer.getUserRolesStorage(main).deleteAllRolesForUser(userId);
StorageLayer.getTOTPStorage(main).deleteAllDataForUser(userId);
}

private static void deleteAuthRecipeUser(Main main, String userId) throws StorageQueryException {
Expand Down
30 changes: 23 additions & 7 deletions src/main/java/io/supertokens/config/CoreConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ public class CoreConfig {
@JsonProperty
private long passwordless_code_lifetime = 900000; // in MS

@JsonProperty
private int totp_rate_limit_window_size = 5;
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved

private final String logDefault = "asdkfahbdfk3kjHS";
@JsonProperty
private String info_log_path = logDefault;
Expand Down Expand Up @@ -106,10 +109,13 @@ public class CoreConfig {
private int bcrypt_log_rounds = 11;

// TODO: add https in later version
// # (OPTIONAL) boolean value (true or false). Set to true if you want to enable https requests to SuperTokens.
// # If you are not running SuperTokens within a closed network along with your API process, for
// # example if you are using multiple cloud vendors, then it is recommended to set this to true.
// # webserver_https_enabled:
// # (OPTIONAL) boolean value (true or false). Set to true if you want to enable
// https requests to SuperTokens.
// # If you are not running SuperTokens within a closed network along with your
// API process, for
// # example if you are using multiple cloud vendors, then it is recommended to
// set this to true.
// # webserver_https_enabled:
@JsonProperty
private boolean webserver_https_enabled = false;

Expand Down Expand Up @@ -191,9 +197,11 @@ public enum PASSWORD_HASHING_ALG {
}

public int getArgon2HashingPoolSize() {
// the reason we do Math.max below is that if the password hashing algo is bcrypt,
// the reason we do Math.max below is that if the password hashing algo is
// bcrypt,
// then we don't check the argon2 hashing pool size config at all. In this case,
// if the user gives a <= 0 number, it crashes the core (since it creates a blockedqueue in PaswordHashing
// if the user gives a <= 0 number, it crashes the core (since it creates a
// blockedqueue in PaswordHashing
// .java with length <= 0). So we do a Math.max
return Math.max(1, argon2_hashing_pool_size);
}
Expand Down Expand Up @@ -266,6 +274,10 @@ public long getPasswordlessCodeLifetime() {
return passwordless_code_lifetime;
}

public int getTotpRateLimitWindowSize() {
return totp_rate_limit_window_size;
}

public boolean isTelemetryDisabled() {
return disable_telemetry;
}
Expand Down Expand Up @@ -384,6 +396,10 @@ void validateAndInitialise(Main main) throws IOException {
throw new QuitProgramException("'passwordless_max_code_input_attempts' must be > 0");
}

if (totp_rate_limit_window_size <= 0) {
throw new QuitProgramException("'totp_rate_limit_window_size' must be > 0");
}
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved

if (max_server_pool_size <= 0) {
throw new QuitProgramException("'max_server_pool_size' must be >= 1. The config file can be found here: "
+ getConfigFileLocation(main));
Expand Down Expand Up @@ -475,4 +491,4 @@ void validateAndInitialise(Main main) throws IOException {
}
}

}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.supertokens.cronjobs.deleteExpiredTotpTokens;

import io.supertokens.Main;
import io.supertokens.ResourceDistributor;
import io.supertokens.pluginInterface.STORAGE_TYPE;
import io.supertokens.pluginInterface.totp.sqlStorage.TOTPSQLStorage;
import io.supertokens.cronjobs.CronTask;
Expand All @@ -15,6 +16,14 @@ private DeleteExpiredTotpTokens(Main main) {
super("DeleteExpiredTotpTokens", main);
}

public static DeleteExpiredTotpTokens getInstance(Main main) {
ResourceDistributor.SingletonResource instance = main.getResourceDistributor().getResource(RESOURCE_KEY);
if (instance == null) {
instance = main.getResourceDistributor().setResource(RESOURCE_KEY, new DeleteExpiredTotpTokens(main));
}
return (DeleteExpiredTotpTokens) instance;
}

@Override
protected void doTask() throws Exception {
if (StorageLayer.getStorage(this.main).getType() != STORAGE_TYPE.SQL) {
Expand Down
62 changes: 30 additions & 32 deletions src/main/java/io/supertokens/inmemorydb/Start.java
Original file line number Diff line number Diff line change
Expand Up @@ -1633,35 +1633,28 @@ public void addInfoToNonAuthRecipesBasedOnUserId(String className, String userId
@Override
public void createDevice(TOTPDevice device) throws StorageQueryException, DeviceAlreadyExistsException {
try {
TOTPQueries.createDevice(this, device);
} catch (SQLException e) {
if (e.getMessage()
.equals("[SQLITE_CONSTRAINT] Abort due to constraint violation (UNIQUE constraint failed: "
+ Config.getConfig(this).getTotpUserDevicesTable() + ".user_id, "
+ Config.getConfig(this).getTotpUserDevicesTable() + ".device_name" + ")")) {
TOTPQueries.createDeviceAndUser(this, device);
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
} catch (StorageTransactionLogicException e) {
String message = e.actualException.getMessage();
if (message.equals("[SQLITE_CONSTRAINT] Abort due to constraint violation (UNIQUE constraint failed: "
+ Config.getConfig(this).getTotpUserDevicesTable() + ".user_id, "
+ Config.getConfig(this).getTotpUserDevicesTable() + ".device_name" + ")")) {
throw new DeviceAlreadyExistsException();
}

throw new StorageQueryException(e);
throw new StorageQueryException(e.actualException);
}
}

@Override
public boolean markDeviceAsVerified(String userId, String deviceName)
public void markDeviceAsVerified(String userId, String deviceName)
throws StorageQueryException, UnknownDeviceException {
try {
int updatedCount = TOTPQueries.markDeviceAsVerified(this, userId, deviceName);
if (updatedCount == 0) {
TOTPDevice[] devices = TOTPQueries.getDevices(this, userId);
for (TOTPDevice device : devices) {
if (device.deviceName.equals(deviceName) && device.verified) {
return true; // Device was already verified
}
}
// Device was not found:
throw new UnknownDeviceException();
}
return false; // Device was marked as verified
return; // Device was marked as verified
} catch (SQLException e) {
throw new StorageQueryException(e);
}
Expand All @@ -1675,12 +1668,8 @@ public void deleteDevice(String userId, String deviceName)
if (deletedCount == 0) {
throw new UnknownDeviceException();
}

// Note: This step is only required for in-memory databases.
// They don't have cascading deletes, so we need to manually delete the codes
TOTPQueries.removeUsedCodes(this, userId, deviceName);
} catch (SQLException e) {
throw new StorageQueryException(e);
} catch (StorageTransactionLogicException e) {
throw new StorageQueryException(e.actualException);
}
}

Expand Down Expand Up @@ -1715,26 +1704,26 @@ public TOTPDevice[] getDevices(String userId)
}

@Override
public boolean insertUsedCode(TOTPUsedCode usedCodeObj)
public void insertUsedCode(TOTPUsedCode usedCodeObj)
throws StorageQueryException, TotpNotEnabledException {
try {
TOTPDevice[] devices = TOTPQueries.getDevices(this, usedCodeObj.userId);
if (devices.length == 0) {
TOTPQueries.insertUsedCode(this, usedCodeObj);
} catch (StorageTransactionLogicException e) {
String message = e.actualException.getMessage();
if (message
.equals("[SQLITE_CONSTRAINT] Abort due to constraint violation (FOREIGN KEY constraint failed)")) {
// No user/device exists for the given usedCodeObj.userId
throw new TotpNotEnabledException();
}
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved

int insertCount = TOTPQueries.insertUsedCode(this, usedCodeObj);
return insertCount == 1;
} catch (SQLException e) {
throw new StorageQueryException(e);
throw new StorageQueryException(e.actualException);
}
}

@Override
public TOTPUsedCode[] getUsedCodes(String userId)
public TOTPUsedCode[] getNonExpiredUsedCodes(String userId)
throws StorageQueryException {
try {
return TOTPQueries.getUsedCodes(this, userId);
return TOTPQueries.getNonExpiredUsedCodesDescOrder(this, userId);
} catch (SQLException e) {
throw new StorageQueryException(e);
}
Expand All @@ -1749,4 +1738,13 @@ public void removeExpiredCodes()
throw new StorageQueryException(e);
}
}

@Override
public void deleteAllDataForUser(String userId) throws StorageQueryException {
try {
TOTPQueries.deleteAllDataForUser(this, userId);
} catch (StorageTransactionLogicException e) {
throw new StorageQueryException(e);
}
}
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
}
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ public String getUserIdMappingTable() {
return "userid_mapping";
}

public String getTotpUsersTable() {
return "totp_users";
}

public String getTotpUserDevicesTable() {
return "totp_user_devices";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,10 @@ public static void createTablesIfNotExists(Start start, Main main) throws SQLExc
update(start, UserIdMappingQueries.getQueryToCreateUserIdMappingTable(start), NO_OP_SETTER);
}

if (!doesTableExists(start, Config.getConfig(start).getTotpUsersTable())) {
getInstance(main).addState(CREATING_NEW_TABLE, null);
update(start, TOTPQueries.getQueryToCreateUsersTable(start), NO_OP_SETTER);
}

if (!doesTableExists(start, Config.getConfig(start).getTotpUserDevicesTable())) {
getInstance(main).addState(CREATING_NEW_TABLE, null);
Expand Down
Loading