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

MOSIP-38604 Fixed security bug in sonar #1382

Merged
merged 2 commits into from
Jan 8, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -327,4 +327,6 @@ private ResidentConstants() {
public static final String DISCARD_DRAFT_ID = "mosip.resident.discard.pending.drafts";
public static final String DISCARD_DRAFT_VERSION = "mosip.resident.discard.pending.drafts.version";
public static final String REG_PROC_CREDENTIAL_PARTNER_POLICY_URL = "mosip.resident.reg-processer-credential-partner-policy-url";

public static final String ALLOWED_URL = "auth.allowed.urls";
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
import static io.mosip.resident.constant.ResidentConstants.API_RESPONSE_TIME_ID;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import io.mosip.resident.util.AvailableClaimUtility;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -142,7 +145,50 @@ public ResponseEntity<Object> physicalCardOrderRedirect(@RequestParam(name = "re
String response = orderCardService.physicalCardOrder(redirectUrl, paymentTransactionId, eventId,
residentFullAddress,individualId,errorCode,errorMessage);
logger.debug("OrderCardController::physicalCardOrderRedirect()::exit");
return ResponseEntity.status(HttpStatus.FOUND).location(URI.create(response)).build();
String safeResponseUrl = validateAndSanitizeUrl(response);

if (safeResponseUrl == null) {
logger.warn("OrderCardController::physicalCardOrderRedirect()::Invalid redirect URL: {}", response);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid redirect URL");
}

return ResponseEntity.status(HttpStatus.FOUND).location(URI.create(safeResponseUrl)).build();

}

private String validateAndSanitizeUrl(String url) {
if (url == null || url.isEmpty()) {
logger.warn("URL is null or empty.");
return null;
}

try {
URI uri = new URI(url);
String host = uri.getHost();
String scheme = uri.getScheme(); // Extract protocol (http/https)
String path = uri.getPath();

// Ensure path is normalized with a trailing slash
String normalizedPath = (path == null || path.isEmpty()) ? "/" : path;

// Reconstruct base URL with scheme, host, and normalized path
String baseUrl = scheme + "://" + host + normalizedPath;

// Example: Whitelisted domains with protocol and trailing slash
List<String> allowedUrls = List.of(Objects.requireNonNull(env.getProperty(ResidentConstants.ALLOWED_URL)));

logger.debug("Validating URL. Constructed Base URL: {}, Allowed URLs: {}", baseUrl, allowedUrls);

if (host != null && scheme != null && allowedUrls.contains(baseUrl)) {
return uri.toString();
}
} catch (URISyntaxException e) {
logger.error("Invalid URL syntax: {}", url, e);
}

logger.warn("URL validation failed for: {}", url);
return null; // URL is invalid or not allowed
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
Expand Down Expand Up @@ -116,6 +117,9 @@ public class OrderCardControllerTest {
@Mock
private AvailableClaimUtility availableClaimUtility;

@Mock
private Environment environment;

@Before
public void setUp() throws Exception {
responseWrapper = new ResponseWrapper<>();
Expand Down Expand Up @@ -149,10 +153,47 @@ public void testPhysicalCardOrder() throws Exception {

@Test
public void testPhysicalCardOrderRedirect() throws Exception {
Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("https://resident.dev1.mosip.net/");
Mockito.when(orderCardService.physicalCardOrder(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(),
Mockito.any(), Mockito.any(), Mockito.any())).thenReturn("URL");
Mockito.any(), Mockito.any(), Mockito.any())).thenReturn("https://resident.dev1.mosip.net/");
mockMvc.perform(MockMvcRequestBuilders.get(
"/physical-card/order-redirect?redirectUrl=aHR0cHM6Ly93d3cubWFkZWludGV4dC5jb20v&paymentTransactionId=12345dsvdvds&eventId=123456&residentFullAddress=fgfhfghgf")).andExpect(status().isFound());
}

@Test
public void testPhysicalCardOrderRedirectFailure() throws Exception {
Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("https://resident.dev2.mosip.net/");
Mockito.when(orderCardService.physicalCardOrder(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(),
Mockito.any(), Mockito.any(), Mockito.any())).thenReturn("https://resident.dev1.mosip.net/");
mockMvc.perform(MockMvcRequestBuilders.get(
"/physical-card/order-redirect?redirectUrl=aHR0cHM6Ly93d3cubWFkZWludGV4dC5jb20v&paymentTransactionId=12345dsvdvds&eventId=123456&residentFullAddress=fgfhfghgf")).andExpect(status().isBadRequest());
}

@Test
public void testPhysicalCardOrderRedirectFailureUrlEmpty() throws Exception {
Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("https://resident.dev2.mosip.net/");
Mockito.when(orderCardService.physicalCardOrder(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(),
Mockito.any(), Mockito.any(), Mockito.any())).thenReturn("");
mockMvc.perform(MockMvcRequestBuilders.get(
"/physical-card/order-redirect?redirectUrl=aHR0cHM6Ly93d3cubWFkZWludGV4dC5jb20v&paymentTransactionId=12345dsvdvds&eventId=123456&residentFullAddress=fgfhfghgf")).andExpect(status().isBadRequest());
}

@Test
public void testPhysicalCardOrderRedirectFailureUrlNull() throws Exception {
Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("https://resident.dev2.mosip.net/");
Mockito.when(orderCardService.physicalCardOrder(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(),
Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(null);
mockMvc.perform(MockMvcRequestBuilders.get(
"/physical-card/order-redirect?redirectUrl=aHR0cHM6Ly93d3cubWFkZWludGV4dC5jb20v&paymentTransactionId=12345dsvdvds&eventId=123456&residentFullAddress=fgfhfghgf")).andExpect(status().isBadRequest());
}

@Test
public void testPhysicalCardOrderRedirectFailureUrlInvalidUrl() throws Exception {
Mockito.when(environment.getProperty(Mockito.anyString())).thenReturn("https://resident.dev2.mosip.net/");
Mockito.when(orderCardService.physicalCardOrder(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(),
Mockito.any(), Mockito.any(), Mockito.any())).thenReturn("https://resident.dev1.mosip.net /");
mockMvc.perform(MockMvcRequestBuilders.get(
"/physical-card/order-redirect?redirectUrl=aHR0cHM6Ly93d3cubWFkZWludGV4dC5jb20v&paymentTransactionId=12345dsvdvds&eventId=123456&residentFullAddress=fgfhfghgf")).andExpect(status().isBadRequest());
}

}
Loading