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 40 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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,22 @@ 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

### Database changes:
- Add new tables for TOTP recipe:
- `totp_users` that stores the users that have enabled TOTP
- `totp_user_devices` that stores devices (each device has its own secret) for each user
- `totp_used_codes` that stores used codes for each user. This is to implement rate limiting and prevent replay attacks.
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved

### New APIs:
- `POST /recipe/totp/device` to create a new device as well as the user if it doesn't exist.
- `POST /recipe/totp/device/verify` to verify a device. This is to ensure that the user has access to the device.
- `POST /recipe/totp/verify` to verify a code and continue the login flow.
- `PUT /recipe/totp/device` to update the name of a device. Name is just a string that the user can set to identify the device.
- `GET /recipe/totp/device/list` to get all devices for a user.
- `POST /recipe/totp/device/remove` to remove a device. If the user has no more devices, the user is also removed.

rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
## [4.4.2] - 2023-03-16

- Adds null check in email normalisation to fix: https://github.com/supertokens/supertokens-node/issues/514
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:
56 changes: 45 additions & 11 deletions ee/src/main/java/io/supertokens/ee/EEFeatureFlag.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.RSAKeyProvider;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.*;
import io.supertokens.ActiveUsers;
import io.supertokens.Main;
import io.supertokens.ProcessState;
import io.supertokens.cronjobs.Cronjobs;
Expand All @@ -21,6 +19,7 @@
import io.supertokens.httpRequest.HttpRequest;
import io.supertokens.httpRequest.HttpResponseException;
import io.supertokens.output.Logging;
import io.supertokens.pluginInterface.ActiveUsersStorage;
import io.supertokens.pluginInterface.KeyValueInfo;
import io.supertokens.pluginInterface.Storage;
import io.supertokens.pluginInterface.exceptions.StorageQueryException;
Expand Down Expand Up @@ -144,15 +143,50 @@ public Boolean getIsLicenseKeyPresent() {

@Override
public JsonObject getPaidFeatureStats() throws StorageQueryException {
JsonObject result = new JsonObject();
JsonObject usageStats = new JsonObject();
EE_FEATURES[] features = getEnabledEEFeaturesFromDbOrCache();
if (Arrays.stream(features).anyMatch(t -> t == EE_FEATURES.DASHBOARD_LOGIN)) {
JsonObject stats = new JsonObject();
int userCount = StorageLayer.getDashboardStorage(main).getAllDashboardUsers().length;
stats.addProperty("user_count", userCount);
result.add(EE_FEATURES.DASHBOARD_LOGIN.toString(), stats);
ActiveUsersStorage activeUsersStorage = StorageLayer.getActiveUsersStorage(main);

for (EE_FEATURES feature : features) {
if (feature == EE_FEATURES.DASHBOARD_LOGIN) {
JsonObject stats = new JsonObject();
int userCount = StorageLayer.getDashboardStorage(main).getAllDashboardUsers().length;
stats.addProperty("user_count", userCount);
usageStats.add(EE_FEATURES.DASHBOARD_LOGIN.toString(), stats);
}
if (feature == EE_FEATURES.TOTP) {
JsonObject totpStats = new JsonObject();
JsonArray totpMauArr = new JsonArray();

for (int i = 0; i < 30; i++) {
long now = System.currentTimeMillis();
long today = now - (now % (24 * 60 * 60 * 1000L));
long timestamp = today - (i * 24 * 60 * 60 * 1000L);

int totpMau = activeUsersStorage.countUsersEnabledTotpAndActiveSince(timestamp);
totpMauArr.add(new JsonPrimitive(totpMau));
}

totpStats.add("maus", totpMauArr);

rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
int totpTotalUsers = activeUsersStorage.countUsersEnabledTotp();
totpStats.addProperty("total_users", totpTotalUsers);
usageStats.add(EE_FEATURES.TOTP.toString(), totpStats);
}
}

JsonArray mauArr = new JsonArray();
for (int i = 0; i < 30; i++) {
long now = System.currentTimeMillis();
long today = now - (now % (24 * 60 * 60 * 1000L));
long timestamp = today - (i * 24 * 60 * 60 * 1000L);

int mau = activeUsersStorage.countUsersActiveSince(timestamp);
mauArr.add(new JsonPrimitive(mau));
}
return result;

usageStats.add("maus", mauArr);
return usageStats;
}

private EE_FEATURES[] verifyLicenseKey(String licenseKey)
Expand Down
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
}
]
}
18 changes: 18 additions & 0 deletions src/main/java/io/supertokens/ActiveUsers.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package io.supertokens;

import io.supertokens.pluginInterface.exceptions.StorageQueryException;
import io.supertokens.storageLayer.StorageLayer;

public class ActiveUsers {

public static void updateLastActive(Main main, String userId) {
try {
StorageLayer.getActiveUsersStorage(main).updateLastActive(userId);
} catch (StorageQueryException ignored) {
}
}

public static int countUsersActiveSince(Main main, long time) throws StorageQueryException {
return StorageLayer.getActiveUsersStorage(main).countUsersActiveSince(time);
}
}
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 {
}
}

}
}
Loading