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 34 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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [unreleased]

- Add TOTP recipe
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved

## [4.4.1] - 2023-03-09

- Normalises email in all APIs in which email was not being
Expand Down
7 changes: 6 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ dependencies {
// https://mvnrepository.com/artifact/com.lambdaworks/scrypt
implementation group: 'com.lambdaworks', name: 'scrypt', version: '1.4.0'

// https://mvnrepository.com/artifact/com.eatthepath/java-otp
implementation group: 'com.eatthepath', name: 'java-otp', version: '0.4.0'
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved

// https://mvnrepository.com/artifact/commons-codec/commons-codec
implementation group: 'commons-codec', name: 'commons-codec', version: '1.15'
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved

compileOnly project(":supertokens-plugin-interface")
testImplementation project(":supertokens-plugin-interface")

Expand Down Expand Up @@ -159,4 +165,3 @@ tasks.withType(Test) {
}
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
}
}

7 changes: 6 additions & 1 deletion config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ core_config_version: 0
# (OPTIONAL | Default: 900000) long value. Time in milliseconds for how long a passwordless code is valid for.
# passwordless_code_lifetime:

# (OPTIONAL | Default: 5) integer value. The maximum number of invalid TOTP attempts that will trigger rate limiting.
# totp_max_attempts:

# (OPTIONAL | Default: 900) integer value. The time in seconds for which the user will be rate limited once totp_max_attempts is crossed.
# totp_rate_limit_cooldown_sec:
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved

# (OPTIONAL | Default: installation directory/logs/info.log) string value. Give the path to a file (on your local
# system) in which the SuperTokens service can write INFO logs to. Set it to "null" if you want it to log to
Expand Down Expand Up @@ -120,4 +125,4 @@ core_config_version: 0

# (OPTIONAL | Default: null). Regex for denying requests from IP addresses that match with the value. Comment this
# value to deny no IP address.
# ip_deny_regex:
# ip_deny_regex:
7 changes: 6 additions & 1 deletion devConfig.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ core_config_version: 0
# (OPTIONAL | Default: 900000) long value. Time in milliseconds for how long a passwordless code is valid for.
# passwordless_code_lifetime:

# (OPTIONAL | Default: 5) integer value. The maximum number of invalid TOTP attempts that will trigger rate limiting.
# totp_max_attempts:

# (OPTIONAL | Default: 900) integer value. The time in seconds for which the user will be rate limited once totp_max_attempts is crossed.
# totp_rate_limit_cooldown_sec:

# (OPTIONAL | Default: installation directory/logs/info.log) string value. Give the path to a file (on your local
# system) in which the SuperTokens service can write INFO logs to. Set it to "null" if you want it to log to
Expand Down Expand Up @@ -120,4 +125,4 @@ disable_telemetry: true

# (OPTIONAL | Default: null). Regex for denying requests from IP addresses that match with the value. Comment this
# value to deny no IP address.
# ip_deny_regex:
# ip_deny_regex:
10 changes: 10 additions & 0 deletions implementationDependencies.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,16 @@
"jar": "https://repo1.maven.org/maven2/com/lambdaworks/scrypt/1.4.0/scrypt-1.4.0.jar",
"name": "Scrypt 1.4.0",
"src": "https://repo1.maven.org/maven2/com/lambdaworks/scrypt/1.4.0/scrypt-1.4.0-sources.jar"
},
{
"jar": "https://repo1.maven.org/maven2/com/eatthepath/java-otp/0.4.0/java-otp-0.4.0.jar",
"name": "Java OTP 0.4.0",
"src": "https://repo1.maven.org/maven2/com/eatthepath/java-otp/0.4.0/java-otp-0.4.0-sources.jar"
},
{
"jar": "https://repo1.maven.org/maven2/commons-codec/commons-codec/1.15/commons-codec-1.15.jar",
"name": "Commons Codec 1.15",
"src": "https://repo1.maven.org/maven2/commons-codec/commons-codec/1.15/commons-codec-1.15-sources.jar"
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
}
]
}
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 @@ -26,6 +26,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 @@ -205,6 +206,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));

// removes expired dashboard session
Cronjobs.addCronjob(this, DeleteExpiredDashboardSessions.getInstance(this));

Expand Down
36 changes: 27 additions & 9 deletions src/main/java/io/supertokens/authRecipe/AuthRecipe.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import io.supertokens.pluginInterface.RECIPE_ID;
import io.supertokens.pluginInterface.authRecipe.AuthRecipeUserInfo;
import io.supertokens.pluginInterface.exceptions.StorageQueryException;
import io.supertokens.pluginInterface.exceptions.StorageTransactionLogicException;
import io.supertokens.pluginInterface.totp.sqlStorage.TOTPSQLStorage;
import io.supertokens.pluginInterface.useridmapping.UserIdMapping;
import io.supertokens.storageLayer.StorageLayer;
import io.supertokens.useridmapping.UserIdType;
Expand Down Expand Up @@ -59,22 +61,30 @@ public static UserPaginationContainer getUsers(Main main, Integer limit, String
return new UserPaginationContainer(resultUsers, nextPaginationToken);
}

public static void deleteUser(Main main, String userId) throws StorageQueryException {
// We clean up the user last so that if anything before that throws an error, then that will throw a 500 to the
// developer. In this case, they expect that the user has not been deleted (which will be true). This is as
// opposed to deleting the user first, in which case if something later throws an error, then the user has
public static void deleteUser(Main main, String userId)
throws StorageQueryException, StorageTransactionLogicException {
// We clean up the user last so that if anything before that throws an error,
// then that will throw a 500 to the
// developer. In this case, they expect that the user has not been deleted
// (which will be true). This is as
// opposed to deleting the user first, in which case if something later throws
// an error, then the user has
// actually been deleted already (which is not expected by the dev)

// For things created after the intial cleanup and before finishing the operation:
// For things created after the intial cleanup and before finishing the
// operation:
// - session: the session will expire anyway
// - email verification: email verification tokens can be created for any userId anyway
// - email verification: email verification tokens can be created for any userId
// anyway

// If userId mapping exists then delete entries with superTokensUserId from auth related tables and
// If userId mapping exists then delete entries with superTokensUserId from auth
// related tables and
// externalUserid from non-auth tables
UserIdMapping userIdMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(main, userId,
UserIdType.ANY);
if (userIdMapping != null) {
// We check if the mapped externalId is another SuperTokens UserId, this could come up when migrating
// We check if the mapped externalId is another SuperTokens UserId, this could
// come up when migrating
// recipes.
// in reference to
// https://docs.google.com/spreadsheets/d/17hYV32B0aDCeLnSxbZhfRN2Y9b0LC2xUF44vV88RNAA/edit?usp=sharing
Expand All @@ -97,12 +107,20 @@ public static void deleteUser(Main main, String userId) throws StorageQueryExcep

}

private static void deleteNonAuthRecipeUser(Main main, String userId) throws StorageQueryException {
private static void deleteNonAuthRecipeUser(Main main, String userId)
throws StorageQueryException, StorageTransactionLogicException {
// non auth recipe deletion
StorageLayer.getUserMetadataStorage(main).deleteUserMetadata(userId);
StorageLayer.getSessionStorage(main).deleteSessionsOfUser(userId);
StorageLayer.getEmailVerificationStorage(main).deleteEmailVerificationUserInfo(userId);
StorageLayer.getUserRolesStorage(main).deleteAllRolesForUser(userId);

TOTPSQLStorage storage = StorageLayer.getTOTPStorage(main);
storage.startTransaction(con -> {
storage.removeUser_Transaction(con, userId);
storage.commitTransaction(con);
return null;
});
}

private static void deleteAuthRecipeUser(Main main, String userId) throws StorageQueryException {
Expand Down
42 changes: 35 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,12 @@ public class CoreConfig {
@JsonProperty
private long passwordless_code_lifetime = 900000; // in MS

@JsonProperty
private int totp_max_attempts = 5;

@JsonProperty
private int totp_rate_limit_cooldown_sec = 900; // in seconds (Default 15 mins)

private final String logDefault = "asdkfahbdfk3kjHS";
@JsonProperty
private String info_log_path = logDefault;
Expand Down Expand Up @@ -106,10 +112,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 +200,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 +277,15 @@ public long getPasswordlessCodeLifetime() {
return passwordless_code_lifetime;
}

public int getTotpMaxAttempts() {
return totp_max_attempts;
}

/** TOTP rate limit cooldown time (in seconds) */
public int getTotpRateLimitCooldownTimeSec() {
return totp_rate_limit_cooldown_sec;
}

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

if (totp_max_attempts <= 0) {
throw new QuitProgramException("'totp_max_attempts' must be > 0");
}

if (totp_rate_limit_cooldown_sec <= 0) {
throw new QuitProgramException("'totp_rate_limit_cooldown_sec' must be > 0");
}

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 +503,4 @@ void validateAndInitialise(Main main) throws IOException {
}
}

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

import io.supertokens.Main;
import io.supertokens.ResourceDistributor;
import io.supertokens.config.Config;
import io.supertokens.pluginInterface.STORAGE_TYPE;
import io.supertokens.pluginInterface.totp.sqlStorage.TOTPSQLStorage;
import io.supertokens.cronjobs.CronTask;
import io.supertokens.cronjobs.CronTaskTest;
import io.supertokens.storageLayer.StorageLayer;
import io.supertokens.output.Logging;

public class DeleteExpiredTotpTokens extends CronTask {
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved

public static final String RESOURCE_KEY = "io.supertokens.cronjobs.deleteExpiredTotpTokens.DeleteExpiredTotpTokens";

rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
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) {
return;
}

TOTPSQLStorage storage = StorageLayer.getTOTPStorage(this.main);

long rateLimitResetInMs = Config.getConfig(this.main).getTotpRateLimitCooldownTimeSec() * 1000;
long expiredBefore = System.currentTimeMillis() - rateLimitResetInMs;

// We will only remove expired codes that have been expired for longer
// than rate limiting duration. This ensures that this DB query
// doesn't delete totp codes that keep the rate limiting active for
// the expected cooldown duration.
int deletedCount = storage.removeExpiredCodes(expiredBefore);
Logging.debug(this.main, "Cron DeleteExpiredTotpTokens deleted " + deletedCount + " expired TOTP codes");
}

@Override
public int getIntervalTimeSeconds() {
if (Main.isTesting) {
Integer interval = CronTaskTest.getInstance(main).getIntervalInSeconds(RESOURCE_KEY);
if (interval != null) {
return interval;
}
}

return 3600; // every hour
}

@Override
public int getInitialWaitTimeSeconds() {
if (!Main.isTesting) {
return getIntervalTimeSeconds();
} else {
return 0;
}
}

}
Loading