-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathTestRoutingTargetHandler.java
More file actions
350 lines (292 loc) · 14.3 KB
/
TestRoutingTargetHandler.java
File metadata and controls
350 lines (292 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.gateway.ha.handler;
import com.google.common.collect.ImmutableMap;
import io.airlift.http.client.HttpClient;
import io.trino.gateway.ha.config.GatewayCookieConfiguration;
import io.trino.gateway.ha.config.GatewayCookieConfigurationPropertiesProvider;
import io.trino.gateway.ha.config.HaGatewayConfiguration;
import io.trino.gateway.ha.config.ProxyBackendConfiguration;
import io.trino.gateway.ha.config.RequestAnalyzerConfig;
import io.trino.gateway.ha.config.RulesExternalConfiguration;
import io.trino.gateway.ha.handler.schema.RoutingTargetResponse;
import io.trino.gateway.ha.router.RoutingGroupSelector;
import io.trino.gateway.ha.router.RoutingManager;
import io.trino.gateway.ha.router.schema.ExternalRouterResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.HttpMethod;
import jakarta.ws.rs.WebApplicationException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static io.trino.gateway.ha.handler.HttpUtils.USER_HEADER;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class TestRoutingTargetHandler
{
private RoutingManager routingManager;
private HttpClient httpClient;
private HttpServletRequest request;
private RoutingTargetHandler handler;
private HaGatewayConfiguration config;
static HaGatewayConfiguration provideGatewayConfiguration()
{
HaGatewayConfiguration config = new HaGatewayConfiguration();
config.setRequestAnalyzerConfig(new RequestAnalyzerConfig());
config.getRouting().setDefaultRoutingGroup("default-group");
// Configure excluded headers
RulesExternalConfiguration rulesExternalConfig = new RulesExternalConfiguration();
rulesExternalConfig.setExcludeHeaders(List.of("Authorization", "Cookie"));
rulesExternalConfig.setUrlPath("http://localhost:8080/api/routing");
config.getRoutingRules().setRulesExternalConfiguration(rulesExternalConfig);
// Initialize cookie configuration
GatewayCookieConfiguration cookieConfig = new GatewayCookieConfiguration();
cookieConfig.setEnabled(false); // Disable cookies for testing
GatewayCookieConfigurationPropertiesProvider.getInstance().initialize(cookieConfig);
return config;
}
private HttpServletRequest prepareMockRequest()
{
HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
when(mockRequest.getMethod()).thenReturn(HttpMethod.GET);
when(mockRequest.getHeader(USER_HEADER)).thenReturn("test-user");
// Set up header names enumeration
List<String> headerNames = List.of(
USER_HEADER,
"Authorization",
"Cookie");
when(mockRequest.getHeaderNames()).thenReturn(Collections.enumeration(headerNames));
// Set up individual header values
when(mockRequest.getHeader("Authorization")).thenReturn("secret-token");
when(mockRequest.getHeader("Cookie")).thenReturn("session-id");
// Set up header values enumeration for each header
when(mockRequest.getHeaders(USER_HEADER)).thenReturn(Collections.enumeration(List.of("test-user")));
when(mockRequest.getHeaders("Authorization")).thenReturn(Collections.enumeration(List.of("secret-token")));
when(mockRequest.getHeaders("Cookie")).thenReturn(Collections.enumeration(List.of("session-id")));
return mockRequest;
}
@BeforeAll
void setUp()
{
config = provideGatewayConfiguration();
httpClient = Mockito.mock(HttpClient.class);
routingManager = Mockito.mock(RoutingManager.class);
request = prepareMockRequest();
// Initialize the handler with the configuration
handler = new RoutingTargetHandler(
routingManager,
RoutingGroupSelector.byRoutingExternal(httpClient, config.getRoutingRules().getRulesExternalConfiguration(), config.getRequestAnalyzerConfig()), config);
}
@BeforeEach
void resetMocks()
{
Mockito.reset(routingManager);
when(routingManager.provideBackendConfiguration(any(), any())).thenReturn(new ProxyBackendConfiguration());
config.getRoutingRules().getRulesExternalConfiguration().setPropagateErrors(false);
}
@Test
void testBasicHeaderModification()
throws Exception
{
// Setup routing group selector response
Map<String, String> modifiedHeaders = ImmutableMap.of(
"X-Original-Header", "new-value",
"X-New-Header", "new-value");
ExternalRouterResponse mockResponse = new ExternalRouterResponse(
"test-group",
Collections.emptyList(),
modifiedHeaders);
when(httpClient.execute(any(), any())).thenReturn(mockResponse);
// Execute
RoutingTargetResponse response = handler.resolveRouting(request);
// Verify
assertThat(response.modifiedRequest().getHeader("X-Original-Header"))
.isEqualTo("new-value");
assertThat(response.modifiedRequest().getHeader("X-New-Header"))
.isEqualTo("new-value");
}
@Test
void testExcludedHeaders()
throws Exception
{
// Setup routing group selector response
Map<String, String> modifiedHeaders = ImmutableMap.of(
"Authorization", "new-token",
"Cookie", "new-session");
ExternalRouterResponse mockResponse = new ExternalRouterResponse(
"test-group",
Collections.emptyList(),
modifiedHeaders);
when(httpClient.execute(any(), any())).thenReturn(mockResponse);
// Execute
RoutingTargetResponse response = handler.resolveRouting(request);
// Verify sensitive headers are not modified
assertThat(response.modifiedRequest().getHeader("Authorization"))
.isEqualTo("secret-token");
assertThat(response.modifiedRequest().getHeader("Cookie"))
.isEqualTo("session-id");
}
@Test
void testNoHeaderModification()
throws Exception
{
// Setup routing group selector response with no header modifications
ExternalRouterResponse mockResponse = new ExternalRouterResponse(
"test-group",
Collections.emptyList(),
ImmutableMap.of());
when(httpClient.execute(any(), any())).thenReturn(mockResponse);
// Execute
RoutingTargetResponse response = handler.resolveRouting(request);
// Verify original headers are preserved
assertThat(response.modifiedRequest().getHeader("X-Original-Header"))
.isNull();
}
@Test
void testEmptyHeader()
throws Exception
{
// Setup routing group selector response
Map<String, String> modifiedHeaders = ImmutableMap.of(
"X-Empty-Header", "",
"X-New-Header", "new-value");
ExternalRouterResponse mockResponse = new ExternalRouterResponse(
"test-group",
Collections.emptyList(),
modifiedHeaders);
when(httpClient.execute(any(), any())).thenReturn(mockResponse);
// Execute
RoutingTargetResponse response = handler.resolveRouting(request);
// Verify
assertThat(response.modifiedRequest().getHeader("X-Empty-Header"))
.isEmpty();
assertThat(response.modifiedRequest().getHeader("X-New-Header"))
.isEqualTo("new-value");
}
@Test
void testEmptyRoutingGroup()
throws Exception
{
// Setup routing group selector response with empty routing group
Map<String, String> modifiedHeaders = ImmutableMap.of(
"X-Empty-Group-Header", "should-be-set");
ExternalRouterResponse mockResponse = new ExternalRouterResponse(
"",
Collections.emptyList(),
modifiedHeaders);
when(httpClient.execute(any(), any())).thenReturn(mockResponse);
// Execute
RoutingTargetResponse response = handler.resolveRouting(request);
// Verify that when no routing group header is set, we default to "adhoc"
assertThat(response.routingDestination().routingGroup()).isEqualTo("default-group");
assertThat(response.modifiedRequest().getHeader("X-Empty-Group-Header"))
.isEqualTo("should-be-set");
}
@Test
void testResponsePropertiesNull()
{
ExternalRouterResponse mockResponse = new ExternalRouterResponse(null, null, ImmutableMap.of());
when(httpClient.execute(any(), any())).thenReturn(mockResponse);
RoutingTargetResponse result = handler.resolveRouting(request);
assertThat(result.routingDestination().routingGroup()).isEqualTo("default-group");
}
@Test
void testResponseGroupSetResponseErrorsNull()
{
ExternalRouterResponse mockResponse = new ExternalRouterResponse(
"test-group", null, ImmutableMap.of());
when(httpClient.execute(any(), any())).thenReturn(mockResponse);
RoutingTargetResponse result = handler.resolveRouting(request);
assertThat(result.routingDestination().routingGroup()).isEqualTo("test-group");
}
@Test
void testPropagateErrorsFalseResponseGroupNullResponseErrorsSet()
{
ExternalRouterResponse mockResponse = new ExternalRouterResponse(null, List.of("some-error"), ImmutableMap.of());
when(httpClient.execute(any(), any())).thenReturn(mockResponse);
RoutingTargetResponse result = handler.resolveRouting(request);
assertThat(result.routingDestination().routingGroup()).isEqualTo("default-group");
}
@Test
void testPropagateErrorsFalseResponseGroupAndErrorsSet()
{
ExternalRouterResponse mockResponse = new ExternalRouterResponse("test-group", List.of("some-error"), ImmutableMap.of());
when(httpClient.execute(any(), any())).thenReturn(mockResponse);
RoutingTargetResponse result = handler.resolveRouting(request);
assertThat(result.routingDestination().routingGroup()).isEqualTo("test-group");
}
@Test
void testPropagateErrorsTrueResponseGroupNullResponseErrorsSet()
{
RoutingTargetHandler handler = createHandlerWithPropagateErrorsTrue();
config.getRoutingRules().getRulesExternalConfiguration().setPropagateErrors(true);
ExternalRouterResponse mockResponse = new ExternalRouterResponse(null, List.of("some-error"), ImmutableMap.of());
when(httpClient.execute(any(), any())).thenReturn(mockResponse);
assertThatThrownBy(() -> handler.resolveRouting(request))
.isInstanceOf(WebApplicationException.class);
}
@Test
void testPropagateErrorsTrueResponseGroupAndErrorsSet()
{
RoutingTargetHandler handler = createHandlerWithPropagateErrorsTrue();
ExternalRouterResponse response = new ExternalRouterResponse("test-group", List.of("some-error"), ImmutableMap.of());
when(httpClient.execute(any(), any())).thenReturn(response);
assertThatThrownBy(() -> handler.resolveRouting(request))
.isInstanceOf(WebApplicationException.class);
}
@Test
void testResolveRoutingWithKnownQueryIdAndFailingFallback()
{
// Simulate a request to /ui/query.html?queryId where the query ID is known
// but the fallback routing (getRoutingTargetResponse) would fail because
// there are no backends for the resolved routing group.
// This tests that the eagerly-evaluated fallback does not throw when
// previousCluster is present.
String queryId = "20240101_000000_00001_aaaaa";
String backendUrl = "https://trino-backend.example.com";
HttpServletRequest uiRequest = Mockito.mock(HttpServletRequest.class);
when(uiRequest.getMethod()).thenReturn(HttpMethod.GET);
when(uiRequest.getRequestURI()).thenReturn("/ui/query.html");
when(uiRequest.getQueryString()).thenReturn(queryId);
// Query ID is known — cache returns the backend
when(routingManager.findBackendForQueryId(queryId)).thenReturn(backendUrl);
when(routingManager.findRoutingGroupForQueryId(queryId)).thenReturn("test-group");
when(routingManager.findExternalUrlForQueryId(queryId)).thenReturn(backendUrl);
// Fallback routing would throw (no backends for the routing group)
when(routingManager.provideBackendConfiguration(any(), any()))
.thenThrow(new IllegalStateException("Number of active backends found zero"));
// With orElse(), this throws. With orElseGet(), this succeeds.
// ref: https://github.com/trinodb/trino-gateway/issues/920
RoutingTargetResponse response = handler.resolveRouting(uiRequest);
assertThat(response.routingDestination().clusterHost()).isEqualTo(backendUrl);
}
private RoutingTargetHandler createHandlerWithPropagateErrorsTrue()
{
config.getRoutingRules().getRulesExternalConfiguration().setPropagateErrors(true);
return new RoutingTargetHandler(
routingManager,
RoutingGroupSelector.byRoutingExternal(httpClient, config.getRoutingRules().getRulesExternalConfiguration(), config.getRequestAnalyzerConfig()), config);
}
}