Skip to content

Commit e748ca5

Browse files
committed
isolate security context changes
1 parent 02e11fd commit e748ca5

File tree

6 files changed

+69
-76
lines changed

6 files changed

+69
-76
lines changed

src/test/java/org/commcare/formplayer/tests/CaseClaimTests.java

+12-28
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,10 @@
11
package org.commcare.formplayer.tests;
22

3-
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
4-
import static org.junit.jupiter.api.Assertions.assertEquals;
5-
import static org.junit.jupiter.api.Assertions.assertFalse;
6-
import static org.junit.jupiter.api.Assertions.assertNotNull;
7-
import static org.junit.jupiter.api.Assertions.assertNull;
8-
import static org.junit.jupiter.api.Assertions.assertThrows;
9-
import static org.junit.jupiter.api.Assertions.assertTrue;
10-
import static org.junit.jupiter.api.Assertions.fail;
11-
import static org.mockito.ArgumentMatchers.any;
12-
import static org.mockito.ArgumentMatchers.anyBoolean;
13-
import static org.mockito.ArgumentMatchers.anyString;
14-
import static org.mockito.Mockito.times;
15-
import static org.mockito.Mockito.verify;
16-
import static org.mockito.Mockito.when;
17-
183
import com.google.common.collect.Multimap;
19-
204
import org.commcare.cases.model.Case;
215
import org.commcare.formplayer.beans.NewFormResponse;
226
import org.commcare.formplayer.beans.SubmitResponseBean;
23-
import org.commcare.formplayer.beans.menus.CommandListResponseBean;
24-
import org.commcare.formplayer.beans.menus.EntityDetailListResponse;
25-
import org.commcare.formplayer.beans.menus.EntityDetailResponse;
26-
import org.commcare.formplayer.beans.menus.EntityListResponse;
27-
import org.commcare.formplayer.beans.menus.QueryResponseBean;
7+
import org.commcare.formplayer.beans.menus.*;
288
import org.commcare.formplayer.junit.RestoreFactoryAnswer;
299
import org.commcare.formplayer.objects.QueryData;
3010
import org.commcare.formplayer.sandbox.SqlStorage;
@@ -45,10 +25,13 @@
4525
import org.springframework.cache.CacheManager;
4626
import org.springframework.cache.caffeine.CaffeineCache;
4727

28+
import javax.annotation.Nullable;
4829
import java.util.HashMap;
4930
import java.util.Hashtable;
5031

51-
import javax.annotation.Nullable;
32+
import static org.junit.jupiter.api.Assertions.*;
33+
import static org.mockito.ArgumentMatchers.*;
34+
import static org.mockito.Mockito.*;
5235

5336
/**
5437
* Regression tests for fixed behaviors
@@ -751,13 +734,14 @@ public void testSplitScreenResponse() throws Exception {
751734
EntityListResponse.class);
752735
assertNull(responseBean.getQueryResponse(),
753736
"Query response attached to entity response when split screen is disabled");
754-
WithHqUserSecurityContextFactory.setSecurityContext(
737+
try (AutoCloseable __ = WithHqUserSecurityContextFactory.setSecurityContext(
755738
HqUserDetails.builder().enabledToggles(new String[]{"SPLIT_SCREEN_CASE_SEARCH"}).build()
756-
);
757-
responseBean = sessionNavigateWithQuery(new String[]{"1", "action 1"},
758-
"caseclaim",
759-
null,
760-
EntityListResponse.class);
739+
)) {
740+
responseBean = sessionNavigateWithQuery(new String[]{"1", "action 1"},
741+
"caseclaim",
742+
null,
743+
EntityListResponse.class);
744+
}
761745
assertNotNull(responseBean.getQueryResponse(),
762746
"No query response attached to entity response when split screen is enabled");
763747
}

src/test/java/org/commcare/formplayer/tests/FormplayerDatadogTests.java

+26-26
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
11
package org.commcare.formplayer.tests;
22

3-
import static org.commcare.formplayer.util.Constants.TOGGLE_DETAILED_TAGGING;
4-
import static org.mockito.Mockito.mock;
5-
import static org.mockito.Mockito.verify;
6-
73
import com.timgroup.statsd.StatsDClient;
8-
94
import org.commcare.formplayer.util.FormplayerDatadog;
105
import org.commcare.formplayer.utils.HqUserDetails;
116
import org.commcare.formplayer.utils.WithHqUserSecurityContextFactory;
@@ -18,6 +13,10 @@
1813
import java.util.Collections;
1914
import java.util.List;
2015

16+
import static org.commcare.formplayer.util.Constants.TOGGLE_DETAILED_TAGGING;
17+
import static org.mockito.Mockito.mock;
18+
import static org.mockito.Mockito.verify;
19+
2120
public class FormplayerDatadogTests {
2221
FormplayerDatadog datadog;
2322
StatsDClient mockDatadogClient;
@@ -103,15 +102,16 @@ public void testTransientTagUsedForRecordExecutionTime() {
103102
}
104103

105104
@Test
106-
public void testAddRequestScopedDetailedTagForEligibleDomain() {
107-
enableDetailTagging();
108-
109-
// detailed_tag was added to FormplayerDatadog in beforeTest
110-
datadog.addRequestScopedTag("detailed_tag", "test_value");
111-
datadog.recordExecutionTime("requests", 100, Collections.emptyList());
112-
String expectedTag = "detailed_tag:test_value";
113-
String[] args = {expectedTag};
114-
verify(mockDatadogClient).recordExecutionTime("requests", 100, args);
105+
public void testAddRequestScopedDetailedTagForEligibleDomain() throws Exception {
106+
try (AutoCloseable __ = enableDetailTagging()) {
107+
108+
// detailed_tag was added to FormplayerDatadog in beforeTest
109+
datadog.addRequestScopedTag("detailed_tag", "test_value");
110+
datadog.recordExecutionTime("requests", 100, Collections.emptyList());
111+
String expectedTag = "detailed_tag:test_value";
112+
String[] args = {expectedTag};
113+
verify(mockDatadogClient).recordExecutionTime("requests", 100, args);
114+
}
115115
}
116116

117117
@Test
@@ -125,16 +125,16 @@ public void testAddRequestScopedDetailedTagForIneligibleDomain() {
125125
}
126126

127127
@Test
128-
public void testAddTransientDetailedTagForEligibleDomain() {
129-
enableDetailTagging();
130-
131-
List<FormplayerDatadog.Tag> transientTags = new ArrayList<>();
132-
// detailed_tag was added to FormplayerDatadog in beforeTest
133-
transientTags.add(new FormplayerDatadog.Tag("detailed_tag", "test_value"));
134-
datadog.recordExecutionTime("requests", 100, transientTags);
135-
String expectedTag = "detailed_tag:test_value";
136-
String[] args = {expectedTag};
137-
verify(mockDatadogClient).recordExecutionTime("requests", 100, args);
128+
public void testAddTransientDetailedTagForEligibleDomain() throws Exception {
129+
try (AutoCloseable __ = enableDetailTagging()) {
130+
List<FormplayerDatadog.Tag> transientTags = new ArrayList<>();
131+
// detailed_tag was added to FormplayerDatadog in beforeTest
132+
transientTags.add(new FormplayerDatadog.Tag("detailed_tag", "test_value"));
133+
datadog.recordExecutionTime("requests", 100, transientTags);
134+
String expectedTag = "detailed_tag:test_value";
135+
String[] args = {expectedTag};
136+
verify(mockDatadogClient).recordExecutionTime("requests", 100, args);
137+
}
138138
}
139139

140140
@Test
@@ -148,8 +148,8 @@ public void testAddTransientDetailedTagForIneligibleDomain() {
148148
verify(mockDatadogClient).recordExecutionTime("requests", 100, args);
149149
}
150150

151-
private void enableDetailTagging() {
152-
WithHqUserSecurityContextFactory.setSecurityContext(
151+
private AutoCloseable enableDetailTagging() {
152+
return WithHqUserSecurityContextFactory.setSecurityContext(
153153
HqUserDetails.builder().enabledToggles(new String[]{TOGGLE_DETAILED_TAGGING}).build()
154154
);
155155
}

src/test/java/org/commcare/formplayer/tests/HqUserDetailsTests.java

+16-12
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import org.junit.jupiter.api.Test;
1010
import org.springframework.security.core.context.SecurityContextHolder;
1111

12+
import java.io.Closeable;
13+
1214
public class HqUserDetailsTests {
1315

1416
@Test
@@ -38,23 +40,25 @@ public void testCommCareUserIsAuthorized() {
3840
}
3941

4042
@Test
41-
public void testFeatureFlagChecker_isToggleEnabled() {
42-
WithHqUserSecurityContextFactory.setSecurityContext(
43+
public void testFeatureFlagChecker_isToggleEnabled() throws Exception {
44+
try (AutoCloseable __ = WithHqUserSecurityContextFactory.setSecurityContext(
4345
HqUserDetails.builder().enabledToggles(new String[]{"toggle_a", "toggle_b"}).build()
44-
);
45-
Assertions.assertTrue(FeatureFlagChecker.isToggleEnabled("toggle_a"));
46-
Assertions.assertTrue(FeatureFlagChecker.isToggleEnabled("toggle_b"));
47-
Assertions.assertFalse(FeatureFlagChecker.isToggleEnabled("toggle_c"));
46+
)) {
47+
Assertions.assertTrue(FeatureFlagChecker.isToggleEnabled("toggle_a"));
48+
Assertions.assertTrue(FeatureFlagChecker.isToggleEnabled("toggle_b"));
49+
Assertions.assertFalse(FeatureFlagChecker.isToggleEnabled("toggle_c"));
50+
}
4851
}
4952

5053
@Test
51-
public void testFeatureFlagChecker_isPreviewEnabled() {
52-
WithHqUserSecurityContextFactory.setSecurityContext(
54+
public void testFeatureFlagChecker_isPreviewEnabled() throws Exception {
55+
try (AutoCloseable __ = WithHqUserSecurityContextFactory.setSecurityContext(
5356
HqUserDetails.builder().enabledPreviews(new String[]{"preview_a", "preview_b"}).build()
54-
);
55-
Assertions.assertTrue(FeatureFlagChecker.isPreviewEnabled("preview_a"));
56-
Assertions.assertTrue(FeatureFlagChecker.isPreviewEnabled("preview_b"));
57-
Assertions.assertFalse(FeatureFlagChecker.isPreviewEnabled("preview_c"));
57+
)) {
58+
Assertions.assertTrue(FeatureFlagChecker.isPreviewEnabled("preview_a"));
59+
Assertions.assertTrue(FeatureFlagChecker.isPreviewEnabled("preview_b"));
60+
Assertions.assertFalse(FeatureFlagChecker.isPreviewEnabled("preview_c"));
61+
}
5862
}
5963

6064
@AfterEach

src/test/java/org/commcare/formplayer/utils/WithHqUserSecurityContextFactory.java

+4-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import org.springframework.security.test.context.support.WithSecurityContextFactory;
88
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
99

10+
import java.io.Closeable;
11+
1012
/**
1113
* A WithSecurityContextFactory that works with {@link WithHqUser}.
1214
*
@@ -28,8 +30,9 @@ public static SecurityContext createSecurityContext(HqUserDetails details) {
2830
return context;
2931
}
3032

31-
public static void setSecurityContext(HqUserDetails details) {
33+
public static AutoCloseable setSecurityContext(HqUserDetails details) {
3234
SecurityContext context = createSecurityContext(details);
3335
SecurityContextHolder.setContext(context);
36+
return SecurityContextHolder::clearContext;
3437
}
3538
}

src/test/java/org/commcare/formplayer/web/client/RestTemplateAuthTest.java

+9-4
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import org.commcare.formplayer.utils.HqUserDetails;
66
import org.commcare.formplayer.utils.MockRestTemplateBuilder;
77
import org.commcare.formplayer.utils.WithHqUserSecurityContextFactory;
8+
import org.junit.jupiter.api.AfterEach;
89
import org.junit.jupiter.api.BeforeEach;
910
import org.junit.jupiter.api.Test;
1011
import org.junit.jupiter.api.extension.ExtendWith;
@@ -43,11 +44,10 @@ class RestTemplateAuthTest {
4344
@Mock
4445
private HttpServletRequest request;
4546

46-
@Mock
47-
ValueOperations<String, String> originTokens;
48-
4947
private final String commcareHost = "https://www.commcarehq.org";
5048
private final String formplayerAuthKey = "authKey";
49+
private AutoCloseable securityContext;
50+
5151

5252
@BeforeEach
5353
public void init() throws URISyntaxException {
@@ -57,11 +57,16 @@ public void init() throws URISyntaxException {
5757
.getRestTemplate();
5858
mockServer = MockRestServiceServer.createServer(restTemplate);
5959
RequestContextHolder.setRequestAttributes(requestAttributes);
60-
WithHqUserSecurityContextFactory.setSecurityContext(
60+
securityContext = WithHqUserSecurityContextFactory.setSecurityContext(
6161
HqUserDetails.builder().username("testUser").authToken(AUTH_TOKEN).build()
6262
);
6363
}
6464

65+
@AfterEach
66+
public void tearDown() throws Exception {
67+
securityContext.close();
68+
}
69+
6570
private void mockGetRequest() {
6671
lenient().when(requestAttributes.getRequest()).thenReturn(request);
6772
}

src/test/java/org/commcare/formplayer/web/client/RestTemplateReplaceHostTest.java

+2-5
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,6 @@ class RestTemplateConfigTest_noCustomization {
2828

2929
private MockRestServiceServer mockServer;
3030

31-
@Mock
32-
ValueOperations<String, String> originTokens;
33-
3431
@BeforeEach
3532
public void init() throws URISyntaxException {
3633
restTemplate = getRestTemplate("https://web");
@@ -39,7 +36,7 @@ public void init() throws URISyntaxException {
3936

4037
protected RestTemplate getRestTemplate(String commcareHost)
4138
throws URISyntaxException {
42-
return new MockRestTemplateBuilder().withCommcareHost("https://web").getRestTemplate();
39+
return new MockRestTemplateBuilder().withCommcareHost(commcareHost).getRestTemplate();
4340
}
4441

4542
protected String getExpectedUrl() {
@@ -67,7 +64,7 @@ class RestTemplateConfigTest_replaceHost extends RestTemplateConfigTest_noCustom
6764
public RestTemplate getRestTemplate(String commcareHost)
6865
throws URISyntaxException {
6966
return new MockRestTemplateBuilder()
70-
.withCommcareHost("https://web")
67+
.withCommcareHost(commcareHost)
7168
.withExternalRequestMode(RestTemplateConfig.MODE_REPLACE_HOST)
7269
.getRestTemplate();
7370
}

0 commit comments

Comments
 (0)