Skip to content

Commit 493b2df

Browse files
committed
Merge remote-tracking branch 'upstream/master' into feat/ci-release-automation
2 parents 1493515 + a6104b9 commit 493b2df

5 files changed

Lines changed: 78 additions & 14 deletions

File tree

‎shenyu-admin/src/test/java/org/apache/shenyu/admin/discovery/ZookeeperClientDiscoveryIntegrationTest.java‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
package org.apache.shenyu.admin.discovery;
1919

2020
import com.google.gson.JsonObject;
21+
import com.sun.net.httpserver.HttpServer;
2122
import jakarta.annotation.Resource;
2223
import org.apache.curator.test.TestingServer;
2324
import org.apache.shenyu.admin.AbstractSpringIntegrationTest;
@@ -42,7 +43,7 @@
4243

4344
import java.io.InputStream;
4445
import java.io.IOException;
45-
import java.net.ServerSocket;
46+
import java.net.InetSocketAddress;
4647
import java.net.URI;
4748
import java.net.http.HttpClient;
4849
import java.net.http.HttpRequest;
@@ -81,7 +82,7 @@ public class ZookeeperClientDiscoveryIntegrationTest extends AbstractSpringInteg
8182

8283
private final List<ShenyuInstanceRegisterRepository> clients = new CopyOnWriteArrayList<>();
8384

84-
private final List<ServerSocket> backends = new CopyOnWriteArrayList<>();
85+
private final List<HttpServer> backends = new CopyOnWriteArrayList<>();
8586

8687
private final List<DiscoverySyncData> snapshots = new CopyOnWriteArrayList<>();
8788

@@ -95,8 +96,8 @@ public void cleanup() throws IOException {
9596
websocket.abort();
9697
}
9798
clients.forEach(this::stopInstance);
98-
for (ServerSocket backend : backends) {
99-
backend.close();
99+
for (HttpServer backend : backends) {
100+
backend.stop(0);
100101
}
101102
List<DiscoveryDO> discoveries = registeredDiscoveries();
102103
discoveries.forEach(discovery -> processorHolder.chooseProcessor("zookeeper").removeDiscovery(discovery));
@@ -180,8 +181,20 @@ public CompletionStage<?> onText(final WebSocket socket, final CharSequence data
180181

181182
private ShenyuInstanceRegisterRepository startInstance(final TestingServer server, final String app, final int port) throws Exception {
182183
// The Admin health checker remains active while testing registry removal.
183-
// Keep registered backends reachable so health eviction cannot replace that event.
184-
backends.add(new ServerSocket(port));
184+
// Answer document pulls too: a listening socket alone blocks the registry event thread.
185+
HttpServer backend = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
186+
backend.createContext("/", exchange -> {
187+
byte[] document = "{\"openapi\":\"3.0.3\",\"info\":{\"title\":\"Discovery fixture\",\"version\":\"1\"},\"paths\":{}}".getBytes(StandardCharsets.UTF_8);
188+
exchange.getResponseHeaders().set("Content-Type", "application/json");
189+
exchange.sendResponseHeaders(200, document.length);
190+
try (java.io.OutputStream output = exchange.getResponseBody()) {
191+
output.write(document);
192+
} finally {
193+
exchange.close();
194+
}
195+
});
196+
backends.add(backend);
197+
backend.start();
185198
String appName = "zk-6525-" + app;
186199
Properties properties = new Properties();
187200
properties.setProperty("name", appName);

‎shenyu-admin/src/test/java/org/apache/shenyu/admin/mode/cluster/service/ShenyuClusterServiceTest.java‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
import java.util.concurrent.TimeUnit;
3838
import java.util.concurrent.atomic.AtomicInteger;
3939

40+
import static org.awaitility.Awaitility.await;
4041
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
4142
import static org.junit.jupiter.api.Assertions.assertEquals;
4243
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -226,15 +227,12 @@ public void testSelectMasterFailureWaitsForNextPeriod() throws InterruptedExcept
226227

227228
@Test
228229
public void testSelectMasterErrorCountTracking() throws Exception {
229-
CountDownLatch errorsOccurred = new CountDownLatch(2);
230-
when(clusterSelectMasterService.selectMaster(anyString(), anyString(), anyString())).thenAnswer(invocation -> {
231-
errorsOccurred.countDown();
232-
throw new RuntimeException("consecutive failure");
233-
});
230+
when(clusterSelectMasterService.selectMaster(anyString(), anyString(), anyString()))
231+
.thenThrow(new RuntimeException("consecutive failure"));
234232

235233
clusterService.start("127.0.0.1", 9195, "/shenyu");
236-
assertTrue(errorsOccurred.await(5, TimeUnit.SECONDS));
237-
assertTrue(clusterService.getSelectMasterErrorCount() >= 2);
234+
// Wait for the catch block to update the count, rather than for entry into the mock.
235+
await().atMost(5, TimeUnit.SECONDS).until(() -> clusterService.getSelectMasterErrorCount() >= 2);
238236

239237
clusterService.shutdown();
240238
}

‎shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-websocket/src/main/java/org/apache/shenyu/plugin/websocket/WebSocketPlugin.java‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,9 @@ protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPlu
104104
return WebFluxResultUtils.result(exchange, error);
105105
}
106106
URI wsRequestUrl = buildWsRealPath(exchange, upstream, shenyuContext);
107-
LOG.info("you websocket urlPath is :{}", wsRequestUrl.toASCIIString());
107+
if (LOG.isDebugEnabled()) {
108+
LOG.debug("websocket upstream url: {}", toLogUrl(wsRequestUrl));
109+
}
108110
HttpHeaders headers = exchange.getRequest().getHeaders();
109111
// The Mono returned by the WebSocket service completes when the upgrade handshake finishes; the
110112
// proxied session then runs on its own subscription. The count therefore has to be attached to the
@@ -129,6 +131,22 @@ private URI buildWsRealPath(final ServerWebExchange exchange, final Upstream ups
129131
return RequestUrlUtils.buildRequestUri(exchange, upstream.buildDomain(protocol));
130132
}
131133

134+
/**
135+
* Describe the upstream url for logging without the query, fragment or user info,
136+
* which may carry credentials such as {@code ?token=...}.
137+
*
138+
* @param uri the upstream url
139+
* @return scheme, host, port and path of the url
140+
*/
141+
static String toLogUrl(final URI uri) {
142+
StringBuilder builder = new StringBuilder();
143+
builder.append(uri.getScheme()).append("://").append(uri.getHost());
144+
if (uri.getPort() != -1) {
145+
builder.append(':').append(uri.getPort());
146+
}
147+
return builder.append(Objects.toString(uri.getRawPath(), "")).toString();
148+
}
149+
132150
private List<String> buildWsProtocols(final HttpHeaders headers) {
133151
List<String> protocols = headers.get(SEC_WEB_SOCKET_PROTOCOL);
134152
if (CollectionUtils.isEmpty(protocols)) {

‎shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-websocket/src/test/java/org/apache/shenyu/plugin/websocket/WebSocketPluginTest.java‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
import reactor.test.StepVerifier;
5353

5454
import java.lang.reflect.Constructor;
55+
import java.lang.reflect.Field;
5556
import java.lang.reflect.InvocationTargetException;
5657
import java.lang.reflect.Method;
5758
import java.net.InetSocketAddress;
@@ -62,6 +63,7 @@
6263
import java.util.stream.Stream;
6364

6465
import static org.junit.jupiter.api.Assertions.assertEquals;
66+
import static org.junit.jupiter.api.Assertions.assertFalse;
6567
import static org.junit.jupiter.api.Assertions.assertNotNull;
6668
import static org.junit.jupiter.api.Assertions.assertNull;
6769
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -215,6 +217,36 @@ public void otherAlgorithmsShouldNotCountTheProxiedSession() {
215217
assertEquals(initial, upstream.getInflight().get());
216218
}
217219

220+
/**
221+
* The query may carry credentials, so the logged url drops it while the proxied url keeps it.
222+
*/
223+
@Test
224+
public void logUrlShouldDropQueryButProxiedUrlShouldKeepIt() throws NoSuchFieldException, IllegalAccessException {
225+
exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/ws/echo?token=secret&access_token=secret").build());
226+
initMockInfo();
227+
AtomicReference<WebSocketHandler> handler = new AtomicReference<>();
228+
when(webSocketService.handleRequest(any(), any())).thenAnswer(call -> {
229+
handler.set(call.getArgument(1));
230+
return Mono.empty();
231+
});
232+
StepVerifier.create(webSocketPlugin.doExecute(exchange, chain, selectorData, ruleData)).verifyComplete();
233+
234+
Field urlField = handler.get().getClass().getDeclaredField("url");
235+
urlField.setAccessible(true);
236+
URI proxied = (URI) urlField.get(handler.get());
237+
assertEquals("token=secret&access_token=secret", proxied.getQuery());
238+
assertFalse(WebSocketPlugin.toLogUrl(proxied).contains("secret"));
239+
}
240+
241+
@Test
242+
public void toLogUrlShouldKeepOnlySchemeHostPortAndPath() {
243+
assertEquals("ws://127.0.0.1:8001/echo",
244+
WebSocketPlugin.toLogUrl(URI.create("ws://user:pass@127.0.0.1:8001/echo?token=abc#frag")));
245+
assertEquals("wss://example.com/a%20b",
246+
WebSocketPlugin.toLogUrl(URI.create("wss://example.com/a%20b?access_token=abc")));
247+
assertEquals("ws://[::1]:8001", WebSocketPlugin.toLogUrl(URI.create("ws://[::1]:8001?token=abc")));
248+
}
249+
218250
/**
219251
* Skip.
220252
*/

‎shenyu-spring-boot-starter/shenyu-spring-boot-starter-gateway/src/test/java/org/apache/shenyu/springboot/starter/netty/ShenyuDualProtocolWebServerTest.java‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
import java.util.concurrent.CountDownLatch;
5353
import java.util.concurrent.TimeUnit;
5454

55+
import static org.awaitility.Awaitility.await;
5556
import static org.junit.jupiter.api.Assertions.assertEquals;
5657
import static org.junit.jupiter.api.Assertions.assertFalse;
5758
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -227,6 +228,8 @@ private void verifyBothProtocols(final NettyReactiveWebServerFactory factory, fi
227228
WebServer server = factory.getWebServer(echoHandler());
228229
try {
229230
server.start();
231+
// Netty invokes doOnBound asynchronously for the additional listener.
232+
await().atMost(Duration.ofSeconds(5)).until(() -> listeners.size() == 2);
230233
assertEquals(2, listeners.size());
231234
assertEquals(listeners.get(0).port(), server.getPort());
232235
assertEquals("https:/gateway", request(true, server.getPort(), "/gateway", sni).block(Duration.ofSeconds(5)));

0 commit comments

Comments
 (0)