Skip to content

Commit f97c6c1

Browse files
fix: improve null Web API response handling (#1676)
* Fix null Web API response handling Fixes #1675 * Move null-response regressions into the existing client suite * Keep null-response HTTP fixtures local to the client tests
1 parent 8a2423f commit f97c6c1

2 files changed

Lines changed: 114 additions & 14 deletions

File tree

‎slack-api-client/src/main/java/com/slack/api/methods/impl/MethodsClientImpl.java‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package com.slack.api.methods.impl;
22

3-
import com.google.gson.Gson;
43
import com.slack.api.RequestConfigurator;
54
import com.slack.api.methods.*;
65
import com.slack.api.methods.request.admin.analytics.AdminAnalyticsGetFileRequest;
@@ -4063,9 +4062,8 @@ public AdminAnalyticsGetFileResponse adminAnalyticsGetFile(AdminAnalyticsGetFile
40634062
String body = response.body().string();
40644063
if (response.isSuccessful()) {
40654064
try {
4066-
Gson gson = GsonFactory.createSnakeCase(slackHttpClient.getConfig());
40674065
AdminAnalyticsGetFileResponse apiResponse =
4068-
gson.fromJson(body, AdminAnalyticsGetFileResponse.class);
4066+
parseJsonResponse(response, body, AdminAnalyticsGetFileResponse.class);
40694067
apiResponse.setHttpResponseHeaders(toLowerCasedKeyMap(response.headers()));
40704068
return apiResponse;
40714069
} finally {
@@ -4269,7 +4267,7 @@ <T extends SlackApiTextResponse> T parseJsonResponseAndRunListeners(
42694267
String body = response.body().string();
42704268
if (response.isSuccessful()) {
42714269
try {
4272-
T apiResponse = GsonFactory.createSnakeCase(slackHttpClient.getConfig()).fromJson(body, clazz);
4270+
T apiResponse = parseJsonResponse(response, body, clazz);
42734271
if (teamId != null) {
42744272
if (apiResponse.isOk()) {
42754273
metricsDatastore.incrementSuccessfulCalls(executorName, teamId, methodName);
@@ -4287,6 +4285,15 @@ <T extends SlackApiTextResponse> T parseJsonResponseAndRunListeners(
42874285
}
42884286
}
42894287

4288+
private <T extends SlackApiResponse> T parseJsonResponse(
4289+
Response response, String body, Class<T> clazz) throws SlackApiException {
4290+
T apiResponse = GsonFactory.createSnakeCase(slackHttpClient.getConfig()).fromJson(body, clazz);
4291+
if (apiResponse == null) {
4292+
// Gson returns null for an empty body, whitespace, or a JSON null value.
4293+
throw new SlackApiException(slackHttpClient.getConfig(), response, body);
4294+
}
4295+
return apiResponse;
4296+
}
42904297

42914298
void runListenersForBinaryResponse(
42924299
Response response) throws SlackApiException {

‎slack-api-client/src/test/java/test_locally/api/methods/MethodsClientImplTest.java‎

Lines changed: 103 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,24 +7,57 @@
77
import com.slack.api.methods.SlackApiException;
88
import com.slack.api.methods.response.api.ApiTestResponse;
99
import com.slack.api.methods.response.conversations.ConversationsInfoResponse;
10+
import com.slack.api.util.http.listener.HttpResponseListener;
11+
import org.eclipse.jetty.server.Server;
12+
import org.eclipse.jetty.server.ServerConnector;
13+
import org.eclipse.jetty.servlet.ServletHandler;
14+
import org.eclipse.jetty.servlet.ServletHolder;
1015
import org.junit.After;
1116
import org.junit.Before;
1217
import org.junit.Test;
13-
import util.MockSlackApiServer;
18+
import util.MockSlackApi;
1419

20+
import javax.servlet.http.HttpServletRequest;
21+
import javax.servlet.http.HttpServletResponse;
1522
import java.io.IOException;
23+
import java.nio.charset.StandardCharsets;
24+
import java.util.ArrayList;
25+
import java.util.List;
1626

27+
import static org.junit.Assert.assertEquals;
1728
import static org.junit.Assert.assertNotNull;
29+
import static org.junit.Assert.assertNull;
30+
import static org.junit.Assert.assertThrows;
1831
import static org.junit.Assert.assertTrue;
1932
import static util.MockSlackApi.ValidToken;
2033

2134
public class MethodsClientImplTest {
2235

23-
MockSlackApiServer slackApiServer = new MockSlackApiServer();
36+
private volatile String responseBody;
37+
private Server slackApiServer;
38+
private String methodsEndpointPrefix;
2439

2540
@Before
2641
public void setup() throws Exception {
42+
slackApiServer = new Server(0);
43+
ServletHandler handler = new ServletHandler();
44+
handler.addServletWithMapping(new ServletHolder(new MockSlackApi() {
45+
@Override
46+
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
47+
if (responseBody == null) {
48+
super.doPost(request, response);
49+
} else {
50+
response.setStatus(200);
51+
response.setContentType("application/json");
52+
response.setHeader("X-Slack-Req-Id", "null-response-test");
53+
response.getWriter().write(responseBody);
54+
}
55+
}
56+
}), "/*");
57+
slackApiServer.setHandler(handler);
2758
slackApiServer.start();
59+
methodsEndpointPrefix = "http://127.0.0.1:"
60+
+ ((ServerConnector) slackApiServer.getConnectors()[0]).getLocalPort() + "/api/";
2861
}
2962

3063
@After
@@ -35,7 +68,7 @@ public void teamDown() throws Exception {
3568
@Test
3669
public void postFormAndParseResponse() throws IOException, SlackApiException {
3770
SlackConfig config = new SlackConfig();
38-
config.setMethodsEndpointUrlPrefix(slackApiServer.getMethodsEndpointPrefix());
71+
config.setMethodsEndpointUrlPrefix(methodsEndpointPrefix);
3972
MethodsClient client = Slack.getInstance(config).methods();
4073
ApiTestResponse response = client.postFormAndParseResponse(
4174
form -> form.add("foo", "bar"),
@@ -48,7 +81,7 @@ public void postFormAndParseResponse() throws IOException, SlackApiException {
4881
@Test(expected = IOException.class)
4982
public void postFormAndParseResponse_IOException() throws IOException, SlackApiException {
5083
SlackConfig config = new SlackConfig();
51-
config.setMethodsEndpointUrlPrefix(slackApiServer.getMethodsEndpointPrefix().replaceFirst(":\\d+/api/$", ":7777/api/")); // invalid
84+
config.setMethodsEndpointUrlPrefix(methodsEndpointPrefix.replaceFirst(":\\d+/api/$", ":7777/api/")); // invalid
5285
MethodsClient client = Slack.getInstance(config).methods();
5386
client.postFormAndParseResponse(
5487
form -> form.add("foo", "bar"),
@@ -60,7 +93,7 @@ public void postFormAndParseResponse_IOException() throws IOException, SlackApiE
6093
@Test
6194
public void postFormWithAuthorizationHeaderAndParseResponse() throws IOException, SlackApiException {
6295
SlackConfig config = new SlackConfig();
63-
config.setMethodsEndpointUrlPrefix(slackApiServer.getMethodsEndpointPrefix());
96+
config.setMethodsEndpointUrlPrefix(methodsEndpointPrefix);
6497
MethodsClient client = Slack.getInstance(config).methods();
6598
ConversationsInfoResponse response = client.postFormWithAuthorizationHeaderAndParseResponse(
6699
form -> form.add("foo", "bar"),
@@ -75,7 +108,7 @@ public void postFormWithAuthorizationHeaderAndParseResponse() throws IOException
75108
@Test(expected = IOException.class)
76109
public void postFormWithAuthorizationHeaderAndParseResponse_IOException() throws IOException, SlackApiException {
77110
SlackConfig config = new SlackConfig();
78-
config.setMethodsEndpointUrlPrefix(slackApiServer.getMethodsEndpointPrefix().replaceFirst(":\\d+/api/$", ":7777/api/")); // invalid
111+
config.setMethodsEndpointUrlPrefix(methodsEndpointPrefix.replaceFirst(":\\d+/api/$", ":7777/api/")); // invalid
79112
MethodsClient client = Slack.getInstance(config).methods();
80113
client.postFormWithAuthorizationHeaderAndParseResponse(
81114
form -> form.add("foo", "bar"),
@@ -88,7 +121,7 @@ public void postFormWithAuthorizationHeaderAndParseResponse_IOException() throws
88121
@Test(expected = SlackApiException.class)
89122
public void postFormWithAuthorizationHeaderAndParseResponse_SlackApiException() throws IOException, SlackApiException {
90123
SlackConfig config = new SlackConfig();
91-
config.setMethodsEndpointUrlPrefix(slackApiServer.getMethodsEndpointPrefix() + "invalid-path"); // invalid
124+
config.setMethodsEndpointUrlPrefix(methodsEndpointPrefix + "invalid-path"); // invalid
92125
MethodsClient client = Slack.getInstance(config).methods();
93126
client.postFormWithAuthorizationHeaderAndParseResponse(
94127
form -> form.add("foo", "bar"),
@@ -101,7 +134,7 @@ public void postFormWithAuthorizationHeaderAndParseResponse_SlackApiException()
101134
@Test
102135
public void postFormWithTokenAndParseResponse() throws IOException, SlackApiException {
103136
SlackConfig config = new SlackConfig();
104-
config.setMethodsEndpointUrlPrefix(slackApiServer.getMethodsEndpointPrefix());
137+
config.setMethodsEndpointUrlPrefix(methodsEndpointPrefix);
105138
MethodsClient client = Slack.getInstance(config).methods();
106139
ConversationsInfoResponse response = client.postFormWithTokenAndParseResponse(
107140
form -> form.add("foo", "bar"),
@@ -116,7 +149,7 @@ public void postFormWithTokenAndParseResponse() throws IOException, SlackApiExce
116149
@Test(expected = IOException.class)
117150
public void postFormWithTokenAndParseResponse_IOException() throws IOException, SlackApiException {
118151
SlackConfig config = new SlackConfig();
119-
config.setMethodsEndpointUrlPrefix(slackApiServer.getMethodsEndpointPrefix().replaceFirst(":\\d+/api/$", ":7777/api/")); // invalid
152+
config.setMethodsEndpointUrlPrefix(methodsEndpointPrefix.replaceFirst(":\\d+/api/$", ":7777/api/")); // invalid
120153
MethodsClient client = Slack.getInstance(config).methods();
121154
client.postFormWithTokenAndParseResponse(
122155
form -> form.add("foo", "bar"),
@@ -129,7 +162,7 @@ public void postFormWithTokenAndParseResponse_IOException() throws IOException,
129162
@Test(expected = SlackApiException.class)
130163
public void postFormWithTokenAndParseResponse_SlackApiException() throws IOException, SlackApiException {
131164
SlackConfig config = new SlackConfig();
132-
config.setMethodsEndpointUrlPrefix(slackApiServer.getMethodsEndpointPrefix() + "invalid-path"); // invalid
165+
config.setMethodsEndpointUrlPrefix(methodsEndpointPrefix + "invalid-path"); // invalid
133166
MethodsClient client = Slack.getInstance(config).methods();
134167
client.postFormWithTokenAndParseResponse(
135168
form -> form.add("foo", "bar"),
@@ -138,4 +171,64 @@ public void postFormWithTokenAndParseResponse_SlackApiException() throws IOExcep
138171
ConversationsInfoResponse.class
139172
);
140173
}
174+
175+
@Test
176+
public void rejectsEmptyResponse() {
177+
assertNullResponses("");
178+
}
179+
180+
@Test
181+
public void rejectsWhitespaceResponse() {
182+
assertNullResponses(" \n\t");
183+
}
184+
185+
@Test
186+
public void rejectsJsonNullResponse() {
187+
assertNullResponses("null");
188+
}
189+
190+
private void assertNullResponses(String body) {
191+
responseBody = body;
192+
List<HttpResponseListener.State> responses = new ArrayList<>();
193+
SlackConfig config = new SlackConfig();
194+
config.setMethodsEndpointUrlPrefix(methodsEndpointPrefix);
195+
config.getMethodsConfig().setStatsEnabled(false);
196+
config.getHttpClientResponseHandlers().add(new HttpResponseListener() {
197+
@Override
198+
public void accept(State state) {
199+
responses.add(state);
200+
}
201+
});
202+
Slack slack = Slack.getInstance(config);
203+
204+
SlackApiException withoutTeamId = assertThrows(SlackApiException.class,
205+
() -> slack.methods().apiTest(r -> r));
206+
assertInvalidResponse(withoutTeamId, body, responses, false);
207+
208+
SlackApiException withTeamId = assertThrows(SlackApiException.class,
209+
() -> slack.methods(ValidToken, "T123").usergroupsList(r -> r));
210+
assertInvalidResponse(withTeamId, body, responses, false);
211+
212+
SlackApiException multipart = assertThrows(SlackApiException.class,
213+
() -> slack.methods(ValidToken, "T123").filesUpload(r ->
214+
r.fileData("test".getBytes(StandardCharsets.UTF_8)).filename("test.txt")));
215+
assertInvalidResponse(multipart, body, responses, true);
216+
217+
SlackApiException analytics = assertThrows(SlackApiException.class,
218+
() -> slack.methods(ValidToken, "T123")
219+
.adminAnalyticsGetFile(r -> r.date("2020-10-20").type("member")));
220+
assertInvalidResponse(analytics, body, responses, false);
221+
}
222+
223+
private void assertInvalidResponse(SlackApiException failure, String body,
224+
List<HttpResponseListener.State> responses, boolean binaryRequest) {
225+
assertEquals(200, failure.getResponse().code());
226+
assertEquals(body, failure.getResponseBody());
227+
assertEquals("null-response-test", failure.getResponse().header("X-Slack-Req-Id"));
228+
assertNull(failure.getError());
229+
assertEquals(1, responses.size());
230+
assertEquals(body, responses.get(0).getParsedResponseBody());
231+
assertEquals(binaryRequest, responses.get(0).isRequestBodyBinary());
232+
responses.clear();
233+
}
141234
}

0 commit comments

Comments
 (0)