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

Updated certificate API changes #62

Open
wants to merge 14 commits into
base: develop
Choose a base branch
from

Conversation

helenKaryamsetty
Copy link
Member

@helenKaryamsetty helenKaryamsetty commented Jan 30, 2025

πŸ“‹ Description

JIRA ID:

Please provide a summary of the change and the motivation behind it. Include relevant context and details.


βœ… Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • πŸ”₯ Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • πŸ›  Refactor (change that is neither a fix nor a new feature)
  • βš™οΈ Config change (configuration file or build script updates)
  • πŸ“š Documentation (updates to docs or readme)
  • πŸ§ͺ Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • πŸš€ Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.

Summary by CodeRabbit

  • New Features

    • Added configuration for ABHA V3 APIs across different environments
    • Updated authentication mechanism for public key retrieval by introducing an authentication token
  • Improvements

    • Enhanced security for public key retrieval process
    • Standardized configuration entries for ABHA V3 services across development, test, and example environments

Copy link
Contributor

coderabbitai bot commented Jan 30, 2025

Walkthrough

This pull request introduces configuration entries for ABHA V3 APIs across multiple environment properties files and updates the CertificateKeyService interface and its implementations. The changes primarily focus on adding a new authentication endpoint for ABHA V3 and modifying methods to include an authentication token when retrieving public keys. The modifications span configuration files and several Java service classes, indicating an enhancement to the ABHA authentication and key retrieval process.

Changes

File Change Summary
src/main/environment/*.properties Added new configuration entry abdmV3UserAuthenticate for ABHA V3 user authentication in CI, DEV, Example, and Test environments
src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java Updated getCertPublicKey() method signature to include ndhmAuthToken parameter
src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java Implemented new method signature with enhanced request handling, headers, and response processing
src/main/java/com/wipro/fhir/service/v3/abha/*ServiceImpl.java Updated method calls to getCertPublicKey() to pass ndhmAuthToken

Possibly related PRs

Suggested reviewers

  • ravishanigarapu

Poem

🐰 Hopping through code with glee,
ABHA V3 keys set free!
Authentication's new dance,
With tokens giving us a chance,
Rabbit's code hops with delight! πŸ”‘

✨ Finishing Touches
  • πŸ“ Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❀️ Share
πŸͺ§ Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

πŸ”­ Outside diff range comments (8)
src/main/environment/common_ci.properties (2)

Line range hint 88-98: Standardize environment variable usage across V3 API configurations.

The configuration shows inconsistent usage of environment variables. Some endpoints use @env.ABDM_BASE_URL@ while others use direct URLs. This could make environment management more difficult.

Consider using environment variables consistently:

abdmV3UserAuthenticate = @env.ABDM_BASE_URL@/api/hiecm/gateway/v3/sessions
-getAuthCertPublicKey = @env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/cert
-requestOtpForEnrollment = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/request/otp
-abhaEnrollByAadhaar = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/enrol/byAadhaar
-printAbhaCard = @env.ABDM_BASE_URL@/abha/api/v3/profile/account/abha-card
-abhaLoginRequestOtp = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/request/otp
-verifyAbhaLogin = @env.ABDM_BASE_URL@/abha/api/v3/profile/login/verify
+getAuthCertPublicKey = @env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/cert
+requestOtpForEnrollment = @env.ABDM_V3_BASE_URL@/abha/api/v3/enrollment/request/otp
+abhaEnrollByAadhaar = @env.ABDM_V3_BASE_URL@/abha/api/v3/enrollment/enrol/byAadhaar
+printAbhaCard = @env.ABDM_V3_BASE_URL@/abha/api/v3/profile/account/abha-card
+abhaLoginRequestOtp = @env.ABDM_V3_BASE_URL@/abha/api/v3/profile/login/request/otp
+verifyAbhaLogin = @env.ABDM_V3_BASE_URL@/abha/api/v3/profile/login/verify

Line range hint 88-98: Ensure consistent environment usage across ABHA V3 endpoints.

The configuration mixes production and sandbox environments:

  • abdmV3UserAuthenticate uses production URL (dev.abdm.gov.in)
  • Other endpoints use sandbox URLs (abhasbx.abdm.gov.in)

This inconsistency could lead to authentication issues in the CI environment.

Consider using environment variables consistently:

-abdmV3UserAuthenticate = @env.ABDM_BASE_URL@/api/hiecm/gateway/v3/sessions
-getAuthCertPublicKey = @env.ABDM_HEALTH_ID_BASE_URL@/api/v1/auth/cert
-requestOtpForEnrollment = @env.ABDM_BASE_URL@/abha/api/v3/enrollment/request/otp
+abdmV3UserAuthenticate = @env.ABDM_V3_BASE_URL@/api/hiecm/gateway/v3/sessions
+getAuthCertPublicKey = @env.ABDM_V3_BASE_URL@/api/v1/auth/cert
+requestOtpForEnrollment = @env.ABDM_V3_BASE_URL@/abha/api/v3/enrollment/request/otp
src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java (3)

Line range hint 106-111: Enhance error handling for encryption operations.

The encryption of loginId should have proper error handling to prevent potential security vulnerabilities. Consider adding specific exception handling for encryption failures.

-            publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken);
-            if (loginMethod.getLoginId() != null) {
-                encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString);
+            try {
+                publicKeyString = certificateKeyService.getCertPublicKey(ndhmAuthToken);
+                if (loginMethod.getLoginId() == null) {
+                    throw new FHIRException("Login ID cannot be null");
+                }
+                encryptedLoginId = encryption.encrypt(loginMethod.getLoginId(), publicKeyString);
+            } catch (Exception e) {
+                logger.error("Failed to encrypt login ID", e);
+                throw new FHIRException("Failed to secure your data. Please try again.");

Also applies to: 174-179, 265-270


Line range hint 89-90: Consider using a dedicated HTTP client configuration.

The class creates new RestTemplate instances for each request. Consider using a configured RestTemplate bean with proper timeout and retry settings.

+    @Value("${rest.template.timeout:5000}")
+    private int timeout;
+
+    @Bean
+    public RestTemplate restTemplate() {
+        RestTemplate restTemplate = new RestTemplate();
+        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
+        factory.setConnectTimeout(timeout);
+        factory.setReadTimeout(timeout);
+        restTemplate.setRequestFactory(factory);
+        return restTemplate;
+    }
+
     @Override
     public String getOtpForEnrollment(String request) throws FHIRException {
         String res = null;
         Map<String, String> responseMap = new HashMap<>();
-        RestTemplate restTemplate = new RestTemplate();
+        RestTemplate restTemplate = restTemplate();

Also applies to: 91-92


Line range hint 428-429: Improve error handling in constructHealthIdResponse.

The method assumes that all required fields are present in the JSON response. Consider adding null checks and proper error handling.

     private void constructHealthIdResponse(HealthIDResponse healthIDResp, JsonObject profile) throws ParseException {
-        healthIDResp.setHealthIdNumber(profile.get("ABHANumber").getAsString());
+        if (!profile.has("ABHANumber")) {
+            throw new FHIRException("ABHA number is missing in the response");
+        }
+        healthIDResp.setHealthIdNumber(profile.get("ABHANumber").getAsString());
+
+        if (!profile.has("phrAddress")) {
+            throw new FHIRException("PHR address is missing in the response");
+        }
         JsonArray phrAddressArray = profile.getAsJsonArray("phrAddress");

Also applies to: 430-431

src/main/environment/common_example.properties (1)

Line range hint 91-97: Use environment variables instead of hardcoded URLs in example configuration.

The example configuration contains hardcoded URLs which may become outdated. Consider using placeholder variables to maintain consistency with other environment files and make updates easier.

Apply this change:

-abdmV3UserAuthenticate = https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions
-getAuthCertPublicKey = https://healthidsbx.abdm.gov.in/api/v1/auth/cert
-requestOtpForEnrollment = https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp
+abdmV3UserAuthenticate = @env.ABDM_V3_BASE_URL@/api/hiecm/gateway/v3/sessions
+getAuthCertPublicKey = @env.ABDM_V3_BASE_URL@/api/v1/auth/cert
+requestOtpForEnrollment = @env.ABDM_V3_BASE_URL@/abha/api/v3/enrollment/request/otp
src/main/environment/common_dev.properties (1)

Line range hint 88-98: Avoid mixing production and sandbox URLs in development environment.

The configuration uses both production (dev.abdm.gov.in) and sandbox (abhasbx.abdm.gov.in) URLs. This mixing of environments could lead to unexpected behavior during development and testing.

Consider using consistent sandbox URLs for the development environment:

-abdmV3UserAuthenticate = https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions
+abdmV3UserAuthenticate = https://abhasbx.abdm.gov.in/api/hiecm/gateway/v3/sessions
src/main/environment/common_test.properties (1)

Standardize test environment URLs to use sandbox endpoints consistently

The review comment is correct. The test configuration file mixes development and sandbox URLs, which could lead to integration issues. This is particularly concerning given that abhaMode=sbx indicates sandbox environment should be used.

URLs that need to be changed to sandbox endpoints:

  • abdmV3UserAuthenticate: Change from dev to sandbox
  • ndhmuserAuthenticate: Change from dev to sandbox
  • generateOTPForCareContext: Change from dev to sandbox
  • validateOTPForCareContext: Change from dev to sandbox
  • generateABDM_NotifySMS: Change from dev to sandbox
  • getAbdmFacilityServicies: Change from dev to sandbox

All ABDM endpoints in the test environment should consistently use the sandbox domain (abhasbx.abdm.gov.in or healthidsbx.abdm.gov.in) to ensure proper integration testing.

πŸ”— Analysis chain

Line range hint 88-98: Standardize environment configuration for test environment.

Similar to the development environment, the test configuration mixes production and sandbox URLs. Additionally, consider adding validation for these endpoints in the test suite.

  1. Standardize URLs to use sandbox environment:
-abdmV3UserAuthenticate = https://dev.abdm.gov.in/api/hiecm/gateway/v3/sessions
+abdmV3UserAuthenticate = https://abhasbx.abdm.gov.in/api/hiecm/gateway/v3/sessions
  1. Verify the endpoints with this script:
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all ABHA V3 endpoints are accessible in test environment

echo "Checking ABHA V3 endpoints accessibility..."
for endpoint in \
    "https://abhasbx.abdm.gov.in/api/hiecm/gateway/v3/sessions" \
    "https://abhasbx.abdm.gov.in/api/v1/auth/cert" \
    "https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp"
do
    response=$(curl -s -o /dev/null -w "%{http_code}" $endpoint)
    if [ $response -eq 000 ]; then
        echo "Warning: Endpoint $endpoint is not accessible"
    fi
done

Length of output: 386


Script:

#!/bin/bash
# Search for different environment URLs in property files
echo "Checking for environment URLs in property files..."
echo -e "\nFiles containing 'dev.abdm.gov.in':"
rg "dev\.abdm\.gov\.in" --type properties

echo -e "\nFiles containing 'abhasbx.abdm.gov.in':"
rg "abhasbx\.abdm\.gov\.in" --type properties

echo -e "\nFiles containing other ABDM domains:"
rg "abdm\.gov\.in" --type properties | grep -v "dev\." | grep -v "abhasbx\."

Length of output: 669


Script:

#!/bin/bash
# Find all .properties files and search for ABDM URLs
echo "Searching .properties files for ABDM URLs..."

# Find all .properties files
properties_files=$(fd -e properties)

if [ -n "$properties_files" ]; then
    echo -e "\nFiles containing 'dev.abdm.gov.in':"
    echo "$properties_files" | xargs grep -l "dev.abdm.gov.in" 2>/dev/null

    echo -e "\nFiles containing 'abhasbx.abdm.gov.in':"
    echo "$properties_files" | xargs grep -l "abhasbx.abdm.gov.in" 2>/dev/null

    echo -e "\nFull content of common_test.properties:"
    cat src/main/environment/common_test.properties 2>/dev/null
else
    echo "No .properties files found"
fi

Length of output: 6923

🧹 Nitpick comments (4)
src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java (1)

45-54: Centralize header creation and reuse across multiple calls.
You are repeatedly building headers with similar entries. Consider extracting a helper method that populates standard headersβ€”improving consistency and reducing the risk of missing or duplicating headers in other parts of the code.

src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java (3)

106-106: Consider caching the public key to reduce API calls.

The getCertPublicKey method is called multiple times with the same ndhmAuthToken. Consider caching the public key for a specific token to avoid redundant API calls, while ensuring proper cache invalidation when the token expires.

@Service
public class CreateAbhaV3ServiceImpl implements CreateAbhaV3Service {
+    private Map<String, CachedPublicKey> publicKeyCache = new ConcurrentHashMap<>();
+
+    @Value("${public.key.cache.duration:300000}")  // 5 minutes default
+    private long publicKeyCacheDuration;
+
+    private String getCachedPublicKey(String ndhmAuthToken) {
+        CachedPublicKey cached = publicKeyCache.get(ndhmAuthToken);
+        if (cached != null && !cached.isExpired()) {
+            return cached.getKey();
+        }
+        String newKey = certificateKeyService.getCertPublicKey(ndhmAuthToken);
+        publicKeyCache.put(ndhmAuthToken, new CachedPublicKey(newKey, publicKeyCacheDuration));
+        return newKey;
+    }
+
+    private static class CachedPublicKey {
+        private final String key;
+        private final long expiryTime;
+
+        public CachedPublicKey(String key, long cacheDuration) {
+            this.key = key;
+            this.expiryTime = System.currentTimeMillis() + cacheDuration;
+        }
+
+        public String getKey() {
+            return key;
+        }
+
+        public boolean isExpired() {
+            return System.currentTimeMillis() > expiryTime;
+        }
+    }

Also applies to: 174-174, 265-265


Line range hint 63-67: Refactor timestamp generation to reduce code duplication.

The timestamp generation logic is duplicated across multiple methods. Consider extracting it into a utility method.

+    private String generateUTCTimestamp() {
+        TimeZone tz = TimeZone.getTimeZone("UTC");
+        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+        df.setTimeZone(tz);
+        return df.format(new Date());
+    }
+
     @Override
     public String getOtpForEnrollment(String request) throws FHIRException {
         // ...
-        TimeZone tz = TimeZone.getTimeZone("UTC");
-        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
-        df.setTimeZone(tz);
-        String nowAsISO = df.format(new Date());
+        String nowAsISO = generateUTCTimestamp();

Also applies to: 156-160, 252-256


Line range hint 58-59: Consider using constructor injection for required dependencies.

The class has multiple required dependencies that are autowired. Consider using constructor injection to make dependencies explicit and improve testability.

 @Service
 public class CreateAbhaV3ServiceImpl implements CreateAbhaV3Service {
-    @Autowired
-    private GenerateSession_NDHMService generateSession_NDHM;
-    @Autowired
-    private Common_NDHMService common_NDHMService;
-    @Autowired
-    HttpUtils httpUtils;
-    @Autowired
-    Encryption encryption;
-    @Autowired
-    HealthIDRepo healthIDRepo;
-    @Autowired
-    CertificateKeyService certificateKeyService;
+    private final GenerateSession_NDHMService generateSession_NDHM;
+    private final Common_NDHMService common_NDHMService;
+    private final HttpUtils httpUtils;
+    private final Encryption encryption;
+    private final HealthIDRepo healthIDRepo;
+    private final CertificateKeyService certificateKeyService;
+
+    public CreateAbhaV3ServiceImpl(
+            GenerateSession_NDHMService generateSession_NDHM,
+            Common_NDHMService common_NDHMService,
+            HttpUtils httpUtils,
+            Encryption encryption,
+            HealthIDRepo healthIDRepo,
+            CertificateKeyService certificateKeyService) {
+        this.generateSession_NDHM = generateSession_NDHM;
+        this.common_NDHMService = common_NDHMService;
+        this.httpUtils = httpUtils;
+        this.encryption = encryption;
+        this.healthIDRepo = healthIDRepo;
+        this.certificateKeyService = certificateKeyService;
+    }

Also applies to: 61-62

πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 7fe11c4 and 82f88e6.

πŸ“’ Files selected for processing (8)
  • src/main/environment/common_ci.properties (1 hunks)
  • src/main/environment/common_dev.properties (1 hunks)
  • src/main/environment/common_example.properties (1 hunks)
  • src/main/environment/common_test.properties (1 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java (1 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java (1 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/CreateAbhaV3ServiceImpl.java (3 hunks)
  • src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (2 hunks)
🧰 Additional context used
πŸ““ Learnings (1)
src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (1)
Learnt from: helenKaryamsetty
PR: PSMRI/FHIR-API#52
File: src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java:84-91
Timestamp: 2024-12-09T16:01:39.809Z
Learning: In the `requestOtpForAbhaLogin` and `verifyAbhaLogin` methods of `LoginAbhaV3ServiceImpl.java`, `loginId` is mandatory, but even if it is null, the process can proceed without input validation.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (4)
src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyServiceImpl.java (2)

40-40: Validate the authorization token's presence and format.
The updated method signature includes ndhmAuthToken. Consider validating that the token is neither null nor empty before proceeding, to avoid unexpected NullPointerException or authentication failures.


58-63: πŸ› οΈ Refactor suggestion

Check for missing 'publicKey' field and non-200 status codes.
Currently, the code retrieves publicKey assuming it always exists in the response for a 200 status. If the field is missing or the status code differs, the method returns null without logging or throwing an exception. This could lead to unhandled null references downstream. Consider rigorous error handling and logging for non-200 responses or malformed responses.

src/main/java/com/wipro/fhir/service/v3/abha/CertificateKeyService.java (1)

7-7: Document the new parameter in the interface.
The ndhmAuthToken parameter changes the contract. Update the method’s documentation to explain the usage and necessity of this token so that implementations and consumers can properly comply.

src/main/java/com/wipro/fhir/service/v3/abha/LoginAbhaV3ServiceImpl.java (1)

93-93: πŸ› οΈ Refactor suggestion

Possibility of null or empty login IDs and tokens.
Lines 93 and 184 now retrieve the public key via getCertPublicKey(ndhmAuthToken), but there is no explicit validation of ndhmAuthToken, nor is there a guard against a null or empty loginId. If loginId is null or empty, encryption and subsequent processes could fail without clear error messages.

Also applies to: 184-184

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant