Skip to content

Commit 4ab04e2

Browse files
hidingmynamezimeg
andauthored
fix: handle non-numeric Retry-After headers on 429 responses (#1674)
MethodsClientImpl, AuditClientImpl, SCIMClientImpl and SCIM2ClientImpl parsed the Retry-After header with Long.valueOf while handling a 429, so a value that is not an integer replaced the API exception with a NumberFormatException. Parse the header in a shared RetryAfterUtil that logs and ignores such a value. The API exception is now always rethrown, and no retry time is recorded for that response. Fixes #1672 Co-authored-by: hidingmyname <hidingmyname@users.noreply.github.com> Co-authored-by: Eden Zimbelman <eden.zimbelman@salesforce.com>
1 parent f97c6c1 commit 4ab04e2

7 files changed

Lines changed: 261 additions & 15 deletions

File tree

‎slack-api-client/src/main/java/com/slack/api/audit/impl/AuditClientImpl.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import com.slack.api.audit.response.SchemasResponse;
1212
import com.slack.api.methods.impl.TeamIdCache;
1313
import com.slack.api.rate_limits.metrics.MetricsDatastore;
14+
import com.slack.api.util.http.RetryAfterUtil;
1415
import com.slack.api.util.http.SlackHttpClient;
1516
import com.slack.api.util.json.GsonFactory;
1617
import okhttp3.Response;
@@ -150,9 +151,8 @@ private <T extends AuditApiResponse> T doGet(String url, Map<String, String> que
150151
}
151152
if (e.getResponse().code() == 429) {
152153
// rate limited
153-
final String retryAfterSeconds = e.getResponse().header("Retry-After");
154-
if (retryAfterSeconds != null) {
155-
long secondsToWait = Long.valueOf(retryAfterSeconds);
154+
final Long secondsToWait = RetryAfterUtil.parseSeconds(e.getResponse().header("Retry-After"));
155+
if (secondsToWait != null) {
156156
long epochMillisToRetry = System.currentTimeMillis() + (secondsToWait * 1000L);
157157
if (enterpriseId != null) {
158158
datastore.setRateLimitedMethodRetryEpochMillis(executorName, enterpriseId, key, epochMillisToRetry);

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

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,7 @@
338338
import com.slack.api.methods.response.workflows.WorkflowsStepFailedResponse;
339339
import com.slack.api.methods.response.workflows.WorkflowsUpdateStepResponse;
340340
import com.slack.api.rate_limits.metrics.MetricsDatastore;
341+
import com.slack.api.util.http.RetryAfterUtil;
341342
import com.slack.api.util.http.SlackHttpClient;
342343
import com.slack.api.util.json.GsonFactory;
343344
import lombok.extern.slf4j.Slf4j;
@@ -4174,9 +4175,8 @@ protected <T extends SlackApiTextResponse> T postFormWithTokenAndParseResponse(
41744175
metricsDatastore.incrementFailedCalls(executorName, teamId, methodName);
41754176
if (e.getResponse().code() == 429) {
41764177
// rate limited
4177-
final String retryAfterSeconds = e.getResponse().header("Retry-After");
4178-
if (retryAfterSeconds != null) {
4179-
long secondsToWait = Long.valueOf(retryAfterSeconds);
4178+
final Long secondsToWait = RetryAfterUtil.parseSeconds(e.getResponse().header("Retry-After"));
4179+
if (secondsToWait != null) {
41804180
long epochMillisToRetry = System.currentTimeMillis() + (secondsToWait * 1000L);
41814181
String key = buildMethodNameAndSuffix(form, methodName);
41824182
metricsDatastore.setRateLimitedMethodRetryEpochMillis(executorName, teamId, key, epochMillisToRetry);
@@ -4218,9 +4218,8 @@ protected <T extends SlackApiTextResponse> T postMultipartAndParseResponse(
42184218
}
42194219
if (e.getResponse().code() == 429) {
42204220
// rate limited
4221-
final String retryAfterSeconds = e.getResponse().header("Retry-After");
4222-
if (retryAfterSeconds != null) {
4223-
long secondsToWait = Long.valueOf(retryAfterSeconds);
4221+
final Long secondsToWait = RetryAfterUtil.parseSeconds(e.getResponse().header("Retry-After"));
4222+
if (secondsToWait != null) {
42244223
long epochMillisToRetry = System.currentTimeMillis() + (secondsToWait * 1000L);
42254224
metricsDatastore.setRateLimitedMethodRetryEpochMillis(executorName, teamId, methodName, epochMillisToRetry);
42264225
}

‎slack-api-client/src/main/java/com/slack/api/scim/impl/SCIMClientImpl.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import com.slack.api.scim.*;
88
import com.slack.api.scim.request.*;
99
import com.slack.api.scim.response.*;
10+
import com.slack.api.util.http.RetryAfterUtil;
1011
import com.slack.api.util.http.SlackHttpClient;
1112
import com.slack.api.util.json.GsonFactory;
1213
import okhttp3.Request;
@@ -272,9 +273,8 @@ private <T> T handle(
272273
}
273274
if (e.getResponse().code() == 429) {
274275
// rate limited
275-
final String retryAfterSeconds = e.getResponse().header("Retry-After");
276-
if (retryAfterSeconds != null) {
277-
long secondsToWait = Long.valueOf(retryAfterSeconds);
276+
final Long secondsToWait = RetryAfterUtil.parseSeconds(e.getResponse().header("Retry-After"));
277+
if (secondsToWait != null) {
278278
long epochMillisToRetry = System.currentTimeMillis() + (secondsToWait * 1000L);
279279
if (enterpriseId != null) {
280280
datastore.setRateLimitedMethodRetryEpochMillis(

‎slack-api-client/src/main/java/com/slack/api/scim2/impl/SCIM2ClientImpl.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import com.slack.api.scim2.*;
99
import com.slack.api.scim2.request.*;
1010
import com.slack.api.scim2.response.*;
11+
import com.slack.api.util.http.RetryAfterUtil;
1112
import com.slack.api.util.http.SlackHttpClient;
1213
import com.slack.api.util.json.GsonFactory;
1314
import lombok.Builder;
@@ -311,9 +312,8 @@ private <T> T handle(
311312
}
312313
if (e.getResponse().code() == 429) {
313314
// rate limited
314-
final String retryAfterSeconds = e.getResponse().header("Retry-After");
315-
if (retryAfterSeconds != null) {
316-
long secondsToWait = Long.valueOf(retryAfterSeconds);
315+
final Long secondsToWait = RetryAfterUtil.parseSeconds(e.getResponse().header("Retry-After"));
316+
if (secondsToWait != null) {
317317
long epochMillisToRetry = System.currentTimeMillis() + (secondsToWait * 1000L);
318318
if (enterpriseId != null) {
319319
datastore.setRateLimitedMethodRetryEpochMillis(
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.slack.api.util.http;
2+
3+
import lombok.extern.slf4j.Slf4j;
4+
5+
@Slf4j
6+
public class RetryAfterUtil {
7+
8+
private RetryAfterUtil() {
9+
}
10+
11+
/**
12+
* Parses a Retry-After header value as a number of seconds.
13+
*
14+
* @param retryAfter the raw header value, which can be null
15+
* @return the number of seconds, or null if the header is missing or is not an integer
16+
*/
17+
public static Long parseSeconds(String retryAfter) {
18+
if (retryAfter == null) {
19+
return null;
20+
}
21+
try {
22+
return Long.valueOf(retryAfter);
23+
} catch (NumberFormatException e) {
24+
log.warn("Ignoring a non-numeric Retry-After header value: {}", retryAfter);
25+
return null;
26+
}
27+
}
28+
}
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
package test_locally.api;
2+
3+
import com.slack.api.Slack;
4+
import com.slack.api.SlackConfig;
5+
import com.slack.api.audit.AuditApiException;
6+
import com.slack.api.methods.MethodsCompletionException;
7+
import com.slack.api.methods.SlackApiException;
8+
import com.slack.api.rate_limits.metrics.MetricsDatastore;
9+
import com.slack.api.scim.SCIMApiException;
10+
import com.slack.api.scim.SCIMEndpointName;
11+
import com.slack.api.scim2.SCIM2ApiException;
12+
import com.slack.api.scim2.SCIM2EndpointName;
13+
import com.slack.api.util.thread.DaemonThreadExecutorServiceProvider;
14+
import org.eclipse.jetty.server.Server;
15+
import org.eclipse.jetty.server.ServerConnector;
16+
import org.eclipse.jetty.servlet.ServletHandler;
17+
import org.eclipse.jetty.servlet.ServletHolder;
18+
import org.junit.After;
19+
import org.junit.Before;
20+
import org.junit.Test;
21+
22+
import javax.servlet.http.HttpServlet;
23+
import javax.servlet.http.HttpServletRequest;
24+
import javax.servlet.http.HttpServletResponse;
25+
import java.io.IOException;
26+
import java.util.UUID;
27+
import java.util.concurrent.ExecutionException;
28+
import java.util.concurrent.TimeUnit;
29+
30+
import static org.hamcrest.CoreMatchers.instanceOf;
31+
import static org.hamcrest.CoreMatchers.is;
32+
import static org.hamcrest.CoreMatchers.notNullValue;
33+
import static org.hamcrest.CoreMatchers.nullValue;
34+
import static org.hamcrest.MatcherAssert.assertThat;
35+
import static org.junit.Assert.assertThrows;
36+
37+
/**
38+
* Tests behavior when a 429 response contains a non-numeric Retry-After header.
39+
*/
40+
public class InvalidRetryAfterHeaderTest {
41+
42+
private static final String TEAM_ID = "T1234567";
43+
44+
private final String executorName = getClass().getName() + "_" + UUID.randomUUID();
45+
private final String token = "xoxb-test-" + UUID.randomUUID();
46+
private volatile String retryAfter = "notanumber";
47+
private Server server;
48+
private SlackConfig config;
49+
private Slack slack;
50+
51+
@Before
52+
public void setup() throws Exception {
53+
server = new Server(0);
54+
ServletHandler handler = new ServletHandler();
55+
handler.addServletWithMapping(new ServletHolder(new HttpServlet() {
56+
@Override
57+
protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
58+
response.setContentType("application/json");
59+
if (request.getRequestURI().equals("/api/auth.test")) {
60+
response.getWriter().write("{\"ok\":true,\"team_id\":\"" + TEAM_ID + "\"}");
61+
return;
62+
}
63+
response.setStatus(429);
64+
if (retryAfter != null) {
65+
response.setHeader("Retry-After", retryAfter);
66+
}
67+
response.getWriter().write("{\"ok\":false,\"error\":\"ratelimited\","
68+
+ "\"Errors\":{\"description\":\"ratelimited\",\"code\":429}}");
69+
}
70+
}), "/*");
71+
server.setHandler(handler);
72+
server.start();
73+
74+
String url = "http://127.0.0.1:" + ((ServerConnector) server.getConnectors()[0]).getLocalPort() + "/api/";
75+
config = new SlackConfig();
76+
// A private provider prevents close() from shutting down other tests' thread pools.
77+
config.setExecutorServiceProvider(new DaemonThreadExecutorServiceProvider());
78+
config.setMethodsEndpointUrlPrefix(url);
79+
config.setAuditEndpointUrlPrefix(url);
80+
config.setScimEndpointUrlPrefix(url);
81+
config.setScim2EndpointUrlPrefix(url);
82+
config.getMethodsConfig().setExecutorName(executorName);
83+
config.getAuditConfig().setExecutorName(executorName);
84+
config.getSCIMConfig().setExecutorName(executorName);
85+
config.getSCIM2Config().setExecutorName(executorName);
86+
config.synchronizeMetricsDatabases();
87+
slack = Slack.getInstance(config);
88+
}
89+
90+
@After
91+
public void tearDown() throws Exception {
92+
try {
93+
slack.close();
94+
} finally {
95+
server.stop();
96+
}
97+
}
98+
99+
@Test
100+
public void nonNumericRetryAfterHeaderShouldThrowSlackApiException() {
101+
SlackApiException e = assertThrows(SlackApiException.class,
102+
() -> slack.methods(token).usersList(r -> r));
103+
assertThat(e.getResponse().code(), is(429));
104+
assertThat(e.getResponse().header("Retry-After"), is("notanumber"));
105+
assertRetryTimeNotRecorded(config.getMethodsConfig().getMetricsDatastore(), "users.list");
106+
}
107+
108+
@Test
109+
public void multipartRequest() {
110+
SlackApiException e = assertThrows(SlackApiException.class,
111+
() -> slack.methods(token).usersSetPhoto(r -> r.imageData(new byte[]{1})));
112+
assertThat(e.getResponse().code(), is(429));
113+
assertThat(e.getResponse().header("Retry-After"), is("notanumber"));
114+
assertRetryTimeNotRecorded(config.getMethodsConfig().getMetricsDatastore(), "users.setPhoto");
115+
}
116+
117+
@Test
118+
public void asyncMethodsClientRejectingRateLimitedCalls() {
119+
config.getMethodsConfig().setRejectRateLimitedCalls(true);
120+
ExecutionException e = assertThrows(ExecutionException.class,
121+
() -> slack.methodsAsync(token).usersList(r -> r).get(10, TimeUnit.SECONDS));
122+
assertThat(e.getCause(), is(instanceOf(MethodsCompletionException.class)));
123+
SlackApiException cause = ((MethodsCompletionException) e.getCause()).getSlackApiException();
124+
assertThat(cause, is(notNullValue()));
125+
assertThat(cause.getResponse().code(), is(429));
126+
assertThat(cause.getResponse().header("Retry-After"), is("notanumber"));
127+
}
128+
129+
@Test
130+
public void auditClient() {
131+
AuditApiException e = assertThrows(AuditApiException.class,
132+
() -> slack.audit(token).getLogs(r -> r));
133+
assertThat(e.getResponse().code(), is(429));
134+
assertThat(e.getResponse().header("Retry-After"), is("notanumber"));
135+
assertRetryTimeNotRecorded(config.getAuditConfig().getMetricsDatastore(), "logs");
136+
}
137+
138+
@Test
139+
public void scimClient() {
140+
SCIMApiException e = assertThrows(SCIMApiException.class,
141+
() -> slack.scim(token).readUser(r -> r.id("W1234567")));
142+
assertThat(e.getResponse().code(), is(429));
143+
assertThat(e.getResponse().header("Retry-After"), is("notanumber"));
144+
assertRetryTimeNotRecorded(config.getSCIMConfig().getMetricsDatastore(), SCIMEndpointName.readUser.name());
145+
}
146+
147+
@Test
148+
public void scim2Client() {
149+
SCIM2ApiException e = assertThrows(SCIM2ApiException.class,
150+
() -> slack.scim2(token).readUser(r -> r.id("W1234567")));
151+
assertThat(e.getResponse().code(), is(429));
152+
assertThat(e.getResponse().header("Retry-After"), is("notanumber"));
153+
assertRetryTimeNotRecorded(config.getSCIM2Config().getMetricsDatastore(), SCIM2EndpointName.readUser.name());
154+
}
155+
156+
@Test
157+
public void numericRetryAfterHeaderIsStillRecorded() {
158+
retryAfter = "30";
159+
assertThrows(SlackApiException.class, () -> slack.methods(token).usersList(r -> r));
160+
assertThrows(SlackApiException.class, () -> slack.methods(token).usersSetPhoto(r -> r.imageData(new byte[]{1})));
161+
assertThrows(AuditApiException.class, () -> slack.audit(token).getLogs(r -> r));
162+
assertThrows(SCIMApiException.class, () -> slack.scim(token).readUser(r -> r.id("W1234567")));
163+
assertThrows(SCIM2ApiException.class, () -> slack.scim2(token).readUser(r -> r.id("W1234567")));
164+
165+
assertRetryTimeRecorded(config.getMethodsConfig().getMetricsDatastore(), "users.list");
166+
assertRetryTimeRecorded(config.getMethodsConfig().getMetricsDatastore(), "users.setPhoto");
167+
assertRetryTimeRecorded(config.getAuditConfig().getMetricsDatastore(), "logs");
168+
assertRetryTimeRecorded(config.getSCIMConfig().getMetricsDatastore(), SCIMEndpointName.readUser.name());
169+
assertRetryTimeRecorded(config.getSCIM2Config().getMetricsDatastore(), SCIM2EndpointName.readUser.name());
170+
}
171+
172+
@Test
173+
public void missingRetryAfterHeader() {
174+
retryAfter = null;
175+
SlackApiException e = assertThrows(SlackApiException.class,
176+
() -> slack.methods(token).usersList(r -> r));
177+
assertThat(e.getResponse().code(), is(429));
178+
assertRetryTimeNotRecorded(config.getMethodsConfig().getMetricsDatastore(), "users.list");
179+
}
180+
181+
private void assertRetryTimeNotRecorded(MetricsDatastore datastore, String methodName) {
182+
assertThat(datastore.getRateLimitedMethodRetryEpochMillis(executorName, TEAM_ID, methodName), is(nullValue()));
183+
}
184+
185+
private void assertRetryTimeRecorded(MetricsDatastore datastore, String methodName) {
186+
assertThat(datastore.getRateLimitedMethodRetryEpochMillis(executorName, TEAM_ID, methodName), is(notNullValue()));
187+
}
188+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package test_locally.api.util.http;
2+
3+
import com.slack.api.util.http.RetryAfterUtil;
4+
import org.junit.Test;
5+
6+
import static org.hamcrest.CoreMatchers.is;
7+
import static org.hamcrest.CoreMatchers.nullValue;
8+
import static org.hamcrest.MatcherAssert.assertThat;
9+
10+
public class RetryAfterUtilTest {
11+
12+
@Test
13+
public void integerSeconds() {
14+
assertThat(RetryAfterUtil.parseSeconds("0"), is(0L));
15+
assertThat(RetryAfterUtil.parseSeconds("30"), is(30L));
16+
}
17+
18+
@Test
19+
public void missing() {
20+
assertThat(RetryAfterUtil.parseSeconds(null), is(nullValue()));
21+
}
22+
23+
@Test
24+
public void notAnInteger() {
25+
assertThat(RetryAfterUtil.parseSeconds(""), is(nullValue()));
26+
assertThat(RetryAfterUtil.parseSeconds("notanumber"), is(nullValue()));
27+
assertThat(RetryAfterUtil.parseSeconds("1.5"), is(nullValue()));
28+
assertThat(RetryAfterUtil.parseSeconds("Wed, 21 Oct 2026 07:28:00 GMT"), is(nullValue()));
29+
assertThat(RetryAfterUtil.parseSeconds("99999999999999999999"), is(nullValue()));
30+
}
31+
}

0 commit comments

Comments
 (0)