Skip to content

Commit a45f700

Browse files
committed
fix(ci): reconcile HTTPS baseline with master discovery fixture
2 parents 98da9ea + a6104b9 commit a45f700

8 files changed

Lines changed: 412 additions & 14 deletions

File tree

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

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -181,15 +181,20 @@ public CompletionStage<?> onText(final WebSocket socket, final CharSequence data
181181

182182
private ShenyuInstanceRegisterRepository startInstance(final TestingServer server, final String app, final int port) throws Exception {
183183
// The Admin health checker remains active while testing registry removal.
184-
// Keep registered backends reachable so health eviction cannot replace that event.
185-
// Swagger discovery must receive a response rather than block the registry event thread.
184+
// Answer document pulls too: a listening socket alone blocks the registry event thread.
186185
HttpServer backend = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
187186
backend.createContext("/", exchange -> {
188-
exchange.sendResponseHeaders(404, -1);
189-
exchange.close();
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+
}
190195
});
191-
backend.start();
192196
backends.add(backend);
197+
backend.start();
193198
String appName = "zk-6525-" + app;
194199
Properties properties = new Properties();
195200
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
}
Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.shenyu.admin.service.impl;
19+
20+
import org.apache.shenyu.admin.listener.DataChangedEvent;
21+
import org.apache.shenyu.admin.mapper.AppAuthMapper;
22+
import org.apache.shenyu.admin.mapper.AppAuthRequestMapper;
23+
import org.apache.shenyu.admin.mapper.AuthParamMapper;
24+
import org.apache.shenyu.admin.mapper.AuthPathMapper;
25+
import org.apache.shenyu.admin.model.dto.AppAuthApplyRequestDTO;
26+
import org.apache.shenyu.admin.model.dto.AppAuthReplacePathsRequestDTO;
27+
import org.apache.shenyu.admin.model.dto.AppAuthResultQueryDTO;
28+
import org.apache.shenyu.admin.model.dto.AppAuthRevokeRequestDTO;
29+
import org.apache.shenyu.admin.model.vo.AppAuthResultVO;
30+
import org.apache.ibatis.session.SqlSessionFactory;
31+
import org.h2.jdbcx.JdbcDataSource;
32+
import org.h2.tools.RunScript;
33+
import org.junit.jupiter.api.AfterAll;
34+
import org.junit.jupiter.api.BeforeAll;
35+
import org.junit.jupiter.api.Test;
36+
import org.mybatis.spring.SqlSessionFactoryBean;
37+
import org.mybatis.spring.mapper.MapperFactoryBean;
38+
import org.springframework.context.ApplicationEventPublisher;
39+
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
40+
import org.springframework.context.annotation.Bean;
41+
import org.springframework.context.annotation.Configuration;
42+
import org.springframework.core.io.ClassPathResource;
43+
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
44+
import org.springframework.transaction.annotation.EnableTransactionManagement;
45+
46+
import javax.sql.DataSource;
47+
import java.nio.charset.StandardCharsets;
48+
import java.nio.file.Paths;
49+
import java.util.List;
50+
import java.util.Objects;
51+
import java.util.concurrent.CopyOnWriteArrayList;
52+
53+
import static org.junit.jupiter.api.Assertions.assertEquals;
54+
import static org.junit.jupiter.api.Assertions.assertNotNull;
55+
import static org.junit.jupiter.api.Assertions.assertNull;
56+
import static org.junit.jupiter.api.Assertions.assertThrows;
57+
import static org.junit.jupiter.api.Assertions.assertTrue;
58+
59+
/**
60+
* Lightweight H2 coverage for the apply/result/revoke/replacePaths transaction service:
61+
* no external MySQL and no system-property gate, so it runs in the default surefire pass
62+
* (the deep MySQL-fixture suites stay in AppAuthApplyTest and friends).
63+
* Covers first apply, same-parameter replay, different-parameter rejection, replacePaths
64+
* null/empty/whole-replace semantics, the result tri-state and the revoke tombstone.
65+
*/
66+
class AppAuthTransactionServiceH2Test {
67+
68+
private static AnnotationConfigApplicationContext context;
69+
70+
private static AppAuthTransactionService txService;
71+
72+
/** Recorded data-changed events (visible after commit). */
73+
private static final List<Object> PUBLISHED_EVENTS = new CopyOnWriteArrayList<>();
74+
75+
@BeforeAll
76+
static void setUp() {
77+
context = new AnnotationConfigApplicationContext(H2TxConfig.class);
78+
txService = context.getBean(AppAuthTransactionService.class);
79+
}
80+
81+
@AfterAll
82+
static void tearDown() {
83+
if (Objects.nonNull(context)) {
84+
context.close();
85+
}
86+
}
87+
88+
private static AppAuthApplyRequestDTO applyRequest(final String requestId) {
89+
final AppAuthApplyRequestDTO dto = new AppAuthApplyRequestDTO();
90+
dto.setNamespaceId("ns-h2");
91+
dto.setRequestId(requestId);
92+
dto.setAppName("h2-app");
93+
dto.setUserId("u1");
94+
dto.setPathList(List.of("/a", "/b"));
95+
return dto;
96+
}
97+
98+
private static AppAuthResultQueryDTO query(final String requestId) {
99+
final AppAuthResultQueryDTO q = new AppAuthResultQueryDTO();
100+
q.setNamespaceId("ns-h2");
101+
q.setRequestId(requestId);
102+
return q;
103+
}
104+
105+
@Test
106+
void applyReplayReplacePathsRevokeLifecycle() {
107+
// first apply: CREATED with credentials, enabled=false/open=true fixed
108+
final AppAuthResultVO first = txService.apply("caller", applyRequest("r1"), "hash-v2");
109+
assertEquals("CREATED", first.getState());
110+
assertNotNull(first.getAppKey());
111+
assertNotNull(first.getAppSecret());
112+
assertEquals(Boolean.FALSE, first.getEnabled());
113+
assertEquals(Boolean.TRUE, first.getOpen());
114+
115+
// same-parameter replay returns the same credentials
116+
final AppAuthResultVO replay = txService.apply("caller", applyRequest("r1"), "hash-v2");
117+
assertEquals(first.getId(), replay.getId());
118+
assertEquals(first.getAppKey(), replay.getAppKey());
119+
120+
// same requestId with different parameters is rejected (the facade supplies the digest, so different
121+
// parameters arrive here as a different digest for the same requestId)
122+
final AppAuthApplyRequestDTO different = applyRequest("r1");
123+
different.setAppName("other-app");
124+
assertThrows(Exception.class, () -> txService.apply("caller", different, "hash-different"));
125+
126+
// replacePaths: null is rejected, empty clears, non-empty replaces as a whole (de-duplicated)
127+
final AppAuthReplacePathsRequestDTO replace = new AppAuthReplacePathsRequestDTO();
128+
replace.setNamespaceId("ns-h2");
129+
replace.setAuthId(first.getId());
130+
replace.setPathList(null);
131+
assertThrows(Exception.class, () -> txService.replacePaths("caller", replace));
132+
replace.setPathList(List.of());
133+
assertEquals(0, txService.replacePaths("caller", replace).getPathList().size());
134+
replace.setPathList(List.of("/x", "/x", "/y"));
135+
final List<String> replaced = txService.replacePaths("caller", replace).getPathList();
136+
assertEquals(2, replaced.size());
137+
assertTrue(replaced.contains("/x") && replaced.contains("/y"));
138+
139+
// result tri-state: NOT_FOUND for unknown keys, CREATED (with credentials) for r1
140+
assertEquals("NOT_FOUND", txService.result("caller", query("r-none")).getState());
141+
final AppAuthResultVO created = txService.result("caller", query("r1"));
142+
assertEquals("CREATED", created.getState());
143+
assertEquals(first.getAppKey(), created.getAppKey());
144+
145+
// revoke is idempotent and installs a tombstone that rejects late applies
146+
final AppAuthRevokeRequestDTO revoke = new AppAuthRevokeRequestDTO();
147+
revoke.setNamespaceId("ns-h2");
148+
revoke.setRequestId("r1");
149+
revoke.setReason("done");
150+
assertEquals("REVOKED", txService.revoke("caller", revoke).getState());
151+
assertEquals("REVOKED", txService.revoke("caller", revoke).getState());
152+
assertEquals("REVOKED", txService.result("caller", query("r1")).getState());
153+
assertNull(txService.result("caller", query("r1")).getAppKey());
154+
assertThrows(Exception.class, () -> txService.apply("caller", applyRequest("r1"), "hash-v2"));
155+
156+
// commit-time sync events fired for create/update/delete
157+
assertTrue(PUBLISHED_EVENTS.stream().allMatch(DataChangedEvent.class::isInstance));
158+
assertTrue(PUBLISHED_EVENTS.size() >= 3);
159+
}
160+
161+
/** H2 in-memory MySQL-mode database initialized from the maintained H2 schema (includes app_auth_request). */
162+
@Configuration
163+
@EnableTransactionManagement
164+
static class H2TxConfig {
165+
166+
@Bean
167+
public DataSource dataSource() throws Exception {
168+
final JdbcDataSource ds = new JdbcDataSource();
169+
ds.setURL("jdbc:h2:mem:appauthtx;MODE=MySQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1");
170+
try (java.sql.Connection connection = ds.getConnection()) {
171+
RunScript.execute(connection, java.nio.file.Files.newBufferedReader(
172+
Paths.get("src/main/resources/sql-script/h2/schema.sql"), StandardCharsets.UTF_8));
173+
}
174+
return ds;
175+
}
176+
177+
@Bean
178+
public DataSourceTransactionManager transactionManager(final DataSource dataSource) {
179+
return new DataSourceTransactionManager(dataSource);
180+
}
181+
182+
@Bean
183+
public SqlSessionFactory sqlSessionFactory(final DataSource dataSource) throws Exception {
184+
final SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
185+
factoryBean.setDataSource(dataSource);
186+
factoryBean.setTypeAliasesPackage("org.apache.shenyu.admin.model.entity");
187+
factoryBean.setMapperLocations(
188+
new ClassPathResource("mappers/app-auth-request-sqlmap.xml"),
189+
new ClassPathResource("mappers/app-auth-sqlmap.xml"),
190+
new ClassPathResource("mappers/auth-param-sqlmap.xml"),
191+
new ClassPathResource("mappers/auth-path-sqlmap.xml"));
192+
return factoryBean.getObject();
193+
}
194+
195+
@Bean
196+
public MapperFactoryBean<AppAuthRequestMapper> appAuthRequestMapper(final SqlSessionFactory factory) {
197+
final MapperFactoryBean<AppAuthRequestMapper> bean = new MapperFactoryBean<>(AppAuthRequestMapper.class);
198+
bean.setSqlSessionFactory(factory);
199+
return bean;
200+
}
201+
202+
@Bean
203+
public MapperFactoryBean<AppAuthMapper> appAuthMapper(final SqlSessionFactory factory) {
204+
final MapperFactoryBean<AppAuthMapper> bean = new MapperFactoryBean<>(AppAuthMapper.class);
205+
bean.setSqlSessionFactory(factory);
206+
return bean;
207+
}
208+
209+
@Bean
210+
public MapperFactoryBean<AuthParamMapper> authParamMapper(final SqlSessionFactory factory) {
211+
final MapperFactoryBean<AuthParamMapper> bean = new MapperFactoryBean<>(AuthParamMapper.class);
212+
bean.setSqlSessionFactory(factory);
213+
return bean;
214+
}
215+
216+
@Bean
217+
public MapperFactoryBean<AuthPathMapper> authPathMapper(final SqlSessionFactory factory) {
218+
final MapperFactoryBean<AuthPathMapper> bean = new MapperFactoryBean<>(AuthPathMapper.class);
219+
bean.setSqlSessionFactory(factory);
220+
return bean;
221+
}
222+
223+
@Bean
224+
public AppAuthTransactionService appAuthTransactionService(final AppAuthRequestMapper requestMapper,
225+
final AppAuthMapper appAuthMapper,
226+
final AuthParamMapper authParamMapper,
227+
final AuthPathMapper authPathMapper) {
228+
// recorder passed directly to the constructor (container injection of ApplicationEventPublisher
229+
// resolves to the ApplicationContext, whose multicaster has no listeners in this bare context)
230+
final ApplicationEventPublisher recorder = PUBLISHED_EVENTS::add;
231+
return new AppAuthTransactionService(requestMapper, appAuthMapper, authParamMapper,
232+
authPathMapper, recorder);
233+
}
234+
}
235+
}

‎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-sdk/shenyu-sdk-httpclient/src/main/java/org/apache/shenyu/sdk/httpclient/HttpShenyuSdkClient.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ public void cancelled() {
181181
return new ShenyuResponse(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(),
182182
Arrays.stream(response.getAllHeaders()).collect(Collectors.groupingBy(Header::getName, HashMap::new,
183183
Collectors.mapping(Header::getValue, Collectors.toCollection(LinkedList::new)))),
184-
EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8), request);
184+
Objects.isNull(response.getEntity()) ? null : EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8), request);
185185
}
186186

187187
private HttpResponse waitForResponse(final Future<HttpResponse> responseFuture) throws IOException {

0 commit comments

Comments
 (0)