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
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>com.iemr.common-API</groupId>
<artifactId>common-api</artifactId>
<version>3.6.1</version>
<version>3.8.0</version>
<packaging>war</packaging>

<name>Common-API</name>
Expand Down
4 changes: 4 additions & 0 deletions src/main/environment/common_ci.properties
Original file line number Diff line number Diff line change
Expand Up @@ -203,5 +203,9 @@ [email protected]_FEEDBACK_RATELIMIT_DAY_LIMIT
[email protected]_FEEDBACK_RATELIMIT_USER_DAY_LIMIT@
[email protected]_FEEDBACK_RATELIMIT_FAIL_WINDOW_MINUTES@
[email protected]_FEEDBACK_RATELIMIT_BACKOFF_MINUTES@
[email protected]_RATELIMIT_ENABLED@
[email protected]_RATELIMIT_MINUTE_LIMIT@
[email protected]_RATELIMIT_HOUR_LIMIT@
[email protected]_RATELIMIT_DAY_LIMIT@
[email protected]_BENEFICIARY_IDS_API_URL@

4 changes: 4 additions & 0 deletions src/main/environment/common_docker.properties
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,8 @@ platform.feedback.ratelimit.day-limit=${PLATFORM_FEEDBACK_RATELIMIT_DAY_LIMIT}
platform.feedback.ratelimit.user-day-limit=${PLATFORM_FEEDBACK_RATELIMIT_USER_DAY_LIMIT}
platform.feedback.ratelimit.fail-window-minutes=${PLATFORM_FEEDBACK_RATELIMIT_FAIL_WINDOW_MINUTES}
platform.feedback.ratelimit.backoff-minutes=${PLATFORM_FEEDBACK_RATELIMIT_BACKOFF_MINUTES}
otp.ratelimit.enabled=${OTP_RATELIMIT_ENABLED}
otp.ratelimit.minute-limit=${OTP_RATELIMIT_MINUTE_LIMIT}
otp.ratelimit.hour-limit=${OTP_RATELIMIT_HOUR_LIMIT}
otp.ratelimit.day-limit=${OTP_RATELIMIT_DAY_LIMIT}
generateBeneficiaryIDs-api-url={GEN_BENEFICIARY_IDS_API_URL}
5 changes: 5 additions & 0 deletions src/main/environment/common_example.properties
Original file line number Diff line number Diff line change
Expand Up @@ -226,5 +226,10 @@ platform.feedback.ratelimit.user-day-limit=50
platform.feedback.ratelimit.fail-window-minutes=5
platform.feedback.ratelimit.backoff-minutes=15

# --- OTP Rate Limiting (per mobile number) ---
otp.ratelimit.minute-limit=3
otp.ratelimit.hour-limit=10
otp.ratelimit.day-limit=20

### generate Beneficiary IDs URL
generateBeneficiaryIDs-api-url=/generateBeneficiaryController/generateBeneficiaryIDs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
package com.iemr.common.controller.beneficiaryConsent;

import com.iemr.common.data.beneficiaryConsent.BeneficiaryConsentRequest;
import com.iemr.common.exception.OtpRateLimitException;
import com.iemr.common.service.beneficiaryOTPHandler.BeneficiaryOTPHandler;
import com.iemr.common.utils.mapper.InputMapper;
import com.iemr.common.utils.response.OutputResponse;
Expand Down Expand Up @@ -58,7 +59,9 @@
logger.info(success.toString());
response.setResponse(success);


} catch (OtpRateLimitException e) {
logger.warn("OTP rate limit hit for sendConsent: " + e.getMessage());

Check warning on line 63 in src/main/java/com/iemr/common/controller/beneficiaryConsent/BeneficiaryConsentController.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Format specifiers should be used instead of string concatenation.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AZzhTQrS74pkHCIi1LxR&open=AZzhTQrS74pkHCIi1LxR&pullRequest=373
response.setError(429, e.getMessage());
} catch (Exception e) {
response.setError(500, "error : " + e);
}
Expand Down Expand Up @@ -105,6 +108,9 @@
else
response.setError(500, "failure");

} catch (OtpRateLimitException e) {
logger.warn("OTP rate limit hit for resendConsent: " + e.getMessage());

Check warning on line 112 in src/main/java/com/iemr/common/controller/beneficiaryConsent/BeneficiaryConsentController.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Format specifiers should be used instead of string concatenation.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AZzhTQrS74pkHCIi1LxS&open=AZzhTQrS74pkHCIi1LxS&pullRequest=373
response.setError(429, e.getMessage());
} catch (Exception e) {
logger.error("error in re-sending Consent : " + e);
response.setError(500, "error : " + e);
Expand Down
30 changes: 30 additions & 0 deletions src/main/java/com/iemr/common/exception/OtpRateLimitException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* AMRIT – Accessible Medical Records via Integrated Technology
* Integrated EHR (Electronic Health Records) Solution
*
* Copyright (C) "Piramal Swasthya Management and Research Institute"
*
* This file is part of AMRIT.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
package com.iemr.common.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
public class OtpRateLimitException extends RuntimeException {
public OtpRateLimitException(String message) { super(message); }
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.iemr.common.repository.sms.SMSTemplateRepository;
import com.iemr.common.repository.sms.SMSTypeRepository;
import com.iemr.common.service.otp.OTPHandler;
import com.iemr.common.service.otp.OtpRateLimiterService;
import com.iemr.common.service.users.IEMRAdminUserServiceImpl;
import com.iemr.common.utils.config.ConfigProperties;
import com.iemr.common.utils.http.HttpUtils;
Expand Down Expand Up @@ -59,6 +60,8 @@
HttpUtils httpUtils;
@Autowired
private IEMRAdminUserServiceImpl iEMRAdminUserServiceImpl;
@Autowired

Check warning on line 63 in src/main/java/com/iemr/common/service/beneficiaryOTPHandler/BeneficiaryOTPHandlerImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this field injection and use constructor injection instead.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AZzhTQnc74pkHCIi1LxP&open=AZzhTQnc74pkHCIi1LxP&pullRequest=373
private OtpRateLimiterService otpRateLimiterService;

final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
@Autowired
Expand Down Expand Up @@ -107,6 +110,7 @@
*/
@Override
public String sendOTP(BeneficiaryConsentRequest obj) throws Exception {
otpRateLimiterService.checkRateLimit(obj.getMobNo());
int otp = generateOTP(obj.getMobNo());
return sendSMS(otp, obj);
}
Expand Down Expand Up @@ -141,6 +145,7 @@
*/
@Override
public String resendOTP(BeneficiaryConsentRequest obj) throws Exception {
otpRateLimiterService.checkRateLimit(obj.getMobNo());
int otp = generateOTP(obj.getMobNo());
return sendSMS(otp, obj);
}
Expand Down
104 changes: 104 additions & 0 deletions src/main/java/com/iemr/common/service/otp/OtpRateLimiterService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* AMRIT – Accessible Medical Records via Integrated Technology
* Integrated EHR (Electronic Health Records) Solution
*
* Copyright (C) "Piramal Swasthya Management and Research Institute"
*
* This file is part of AMRIT.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
package com.iemr.common.service.otp;

import com.iemr.common.exception.OtpRateLimitException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.concurrent.TimeUnit;

/**
* Rate-limits OTP send/resend requests per mobile number using Redis counters.
*
* Limits (configurable via properties):
* otp.ratelimit.minute-limit – max OTPs per minute (default 3)
* otp.ratelimit.hour-limit – max OTPs per hour (default 10)
* otp.ratelimit.day-limit – max OTPs per day (default 20)
*
* Redis key pattern:
* rl:otp:min:{mobNo}:{minuteSlot} TTL 60 s
* rl:otp:hr:{mobNo}:{hourSlot} TTL 3600 s
* rl:otp:day:{mobNo}:{yyyyMMdd} TTL 86400 s
*/
@Component
public class OtpRateLimiterService {

private final StringRedisTemplate redis;

@Value("${otp.ratelimit.enabled:true}")
private boolean enabled;

@Value("${otp.ratelimit.minute-limit:3}")
private int minuteLimit;

@Value("${otp.ratelimit.hour-limit:10}")
private int hourLimit;

@Value("${otp.ratelimit.day-limit:20}")
private int dayLimit;

public OtpRateLimiterService(StringRedisTemplate redis) {
this.redis = redis;
}

/**
* Checks all three rate-limit windows for the given mobile number.
* Throws {@link OtpRateLimitException} if any limit is exceeded.
* No-op when otp.ratelimit.enabled=false.
*/
public void checkRateLimit(String mobNo) {
if (!enabled) return;
String today = LocalDate.now(ZoneId.of("Asia/Kolkata"))
.toString().replaceAll("-", ""); // yyyyMMdd

Check failure on line 75 in src/main/java/com/iemr/common/service/otp/OtpRateLimiterService.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace this call to "replaceAll()" by a call to the "replace()" method.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Common-API&issues=AZzhTQq374pkHCIi1LxQ&open=AZzhTQq374pkHCIi1LxQ&pullRequest=373
long minuteSlot = System.currentTimeMillis() / 60_000L;
long hourSlot = System.currentTimeMillis() / 3_600_000L;

String minKey = "rl:otp:min:" + mobNo + ":" + minuteSlot;
String hourKey = "rl:otp:hr:" + mobNo + ":" + hourSlot;
String dayKey = "rl:otp:day:" + mobNo + ":" + today;

if (incrementWithExpire(minKey, 60L) > minuteLimit) {
throw new OtpRateLimitException(
"OTP request limit exceeded. Maximum " + minuteLimit + " OTPs allowed per minute. Please try again later.");
}
if (incrementWithExpire(hourKey, 3600L) > hourLimit) {
throw new OtpRateLimitException(
"OTP request limit exceeded. Maximum " + hourLimit + " OTPs allowed per hour. Please try again later.");
}
if (incrementWithExpire(dayKey, 86400L) > dayLimit) {
throw new OtpRateLimitException(
"OTP request limit exceeded. Maximum " + dayLimit + " OTPs allowed per day. Please try again tomorrow.");
}
}

private long incrementWithExpire(String key, long ttlSeconds) {
Long value = redis.opsForValue().increment(key, 1L);
if (value != null && value == 1L) {
redis.expire(key, ttlSeconds, TimeUnit.SECONDS);
}
return value == null ? 0L : value;
}
}
Loading