Skip to content

Commit

Permalink
FM2-616: Fix authentication filter test
Browse files Browse the repository at this point in the history
  • Loading branch information
ibacher committed Mar 11, 2024
1 parent 6b3e271 commit f0b1ae5
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public Dosage toFhirResource(@Nonnull DrugOrder drugOrder) {
doseAndRate.setDose(dose);
dosage.addDoseAndRate(doseAndRate);
}

return dosage;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.when;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,13 @@
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hl7.fhir.r4.utils.client.FHIRToolingClient.DATE_FORMAT;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.when;

import java.text.ParseException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang3.time.DateUtils;
import org.hl7.fhir.r4.model.BooleanType;
import org.hl7.fhir.r4.model.CodeableConcept;
import org.hl7.fhir.r4.model.Coding;
Expand Down Expand Up @@ -227,7 +223,7 @@ public void toFhirResource_shouldReturnDosageWhenSubmittingDrugOrderWithDoseUnit
drugOrder.setAsNeeded(Boolean.TRUE);
drugOrder.setDosingInstructions(DOSING_INSTRUCTION);
Dosage result = dosageTranslator.toFhirResource(drugOrder);

assertThat(result, notNullValue());
assertThat(result.getAsNeededBooleanType().booleanValue(), is(true));
assertThat(result.getText(), equalTo(DOSING_INSTRUCTION));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.openmrs.api.context.Context;
import org.openmrs.api.context.UsernamePasswordAuthenticationScheme;
import org.openmrs.api.context.UsernamePasswordCredentials;

public class AuthenticationFilter implements Filter {
Expand Down Expand Up @@ -52,7 +51,8 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
basicAuth = basicAuth.substring(6); // remove the leading "Basic "
String decoded = new String(Base64.decodeBase64(basicAuth), StandardCharsets.UTF_8);
String[] userAndPass = decoded.split(":");
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userAndPass[0], userAndPass[1]);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userAndPass[0],
userAndPass[1]);
Context.authenticate(credentials);
}
catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;

import org.junit.After;
Expand All @@ -23,8 +27,14 @@
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.openmrs.User;
import org.openmrs.api.context.Authenticated;
import org.openmrs.api.context.AuthenticationScheme;
import org.openmrs.api.context.BasicAuthenticated;
import org.openmrs.api.context.Context;
import org.openmrs.api.context.ContextAuthenticationException;
import org.openmrs.api.context.Credentials;
import org.openmrs.api.context.ServiceContext;
import org.openmrs.api.context.UsernamePasswordCredentials;
import org.openmrs.api.db.ContextDAO;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.web.MockFilterChain;
Expand All @@ -48,9 +58,42 @@ public class AuthenticationFilterTest {
@Mock
private User user;

static class InMemoryAuthenticationScheme implements AuthenticationScheme {

@Override
public Authenticated authenticate(Credentials credentials) throws ContextAuthenticationException {
if (!(credentials instanceof UsernamePasswordCredentials)) {
throw new ContextAuthenticationException(
"The provided credentials could not be used to authenticated with the specified authentication scheme.");
} else {
UsernamePasswordCredentials userPassCreds = (UsernamePasswordCredentials) credentials;
if (userPassCreds.getUsername().equals(USERNAME) && userPassCreds.getPassword().equals(PASSWORD)) {
User user = new User();
user.setUsername(userPassCreds.getUsername());
return new BasicAuthenticated(user, "IN MEMORY AUTH SCHEME");
} else {
throw new ContextAuthenticationException();
}
}
}
}

@Before
public void setup() {
public void setup() throws NoSuchFieldException, IllegalAccessException {
Context.setDAO(contextDAO);

ServiceContext mockServiceContext = mock(ServiceContext.class);
Class<?> serviceContextHolderClass = ServiceContext.class.getDeclaredClasses()[0];
Field instanceField = serviceContextHolderClass.getDeclaredField("instance");
instanceField.setAccessible(true);
instanceField.set(null, mockServiceContext);

when(mockServiceContext.getRegisteredComponents(any())).thenReturn(new ArrayList<>(0));

Field authSchemeField = Context.class.getDeclaredField("authenticationScheme");
authSchemeField.setAccessible(true);
authSchemeField.set(null, new InMemoryAuthenticationScheme());

Context.openSession();

authenticationFilter = new AuthenticationFilter();
Expand All @@ -64,8 +107,6 @@ public void tearDown() {

@Test
public void shouldLoginWithBasicAuthentication() throws Exception {
when(contextDAO.authenticate(USERNAME, PASSWORD)).thenReturn(user);

MockHttpServletRequest servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();

Expand All @@ -80,14 +121,12 @@ public void shouldLoginWithBasicAuthentication() throws Exception {

@Test
public void shouldReturn401WhenAuthenticationFails() throws Exception {
when(contextDAO.authenticate(USERNAME, PASSWORD)).thenThrow(new ContextAuthenticationException());

MockHttpServletRequest servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();

servletRequest.setRequestURI("/openmrs/ws/fhir2/Patient?_id=aa1c7cf0-6a54-4a06-9d77-b26107ad9144");
servletRequest.addHeader(HttpHeaders.AUTHORIZATION,
"Basic " + Base64.getEncoder().encodeToString((USERNAME + ":" + PASSWORD).getBytes(StandardCharsets.UTF_8)));
servletRequest.addHeader(HttpHeaders.AUTHORIZATION, "Basic "
+ Base64.getEncoder().encodeToString((USERNAME + ":" + "badpassword").getBytes(StandardCharsets.UTF_8)));

authenticationFilter.doFilter(servletRequest, servletResponse, filterChain);

Expand All @@ -100,8 +139,6 @@ public void shouldBypassAuthenticationForConformanceStatement() throws Exception
MockHttpServletResponse servletResponse = new MockHttpServletResponse();

servletRequest.setRequestURI("/openmrs/ws/fhir2/metadata");
servletRequest.addHeader(HttpHeaders.AUTHORIZATION,
"Basic " + Base64.getEncoder().encodeToString((USERNAME + ":" + PASSWORD).getBytes(StandardCharsets.UTF_8)));

authenticationFilter.doFilter(servletRequest, servletResponse, filterChain);

Expand All @@ -114,8 +151,6 @@ public void shouldBypassAuthenticationForWellKnownDirectory() throws Exception {
MockHttpServletResponse servletResponse = new MockHttpServletResponse();

servletRequest.setRequestURI("/openmrs/ws/fhir2/.well-known/config.json");
servletRequest.addHeader(HttpHeaders.AUTHORIZATION,
"Basic " + Base64.getEncoder().encodeToString((USERNAME + ":" + PASSWORD).getBytes(StandardCharsets.UTF_8)));

authenticationFilter.doFilter(servletRequest, servletResponse, filterChain);

Expand Down

0 comments on commit f0b1ae5

Please sign in to comment.