Skip to content

Commit 879300f

Browse files
committed
fix(bootstrap): gate local management controllers with the local feature state (#8221)
1 parent a87a361 commit 879300f

10 files changed

Lines changed: 157 additions & 14 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ docker run -d --name shenyu-bootstrap --network shenyu -p 127.0.0.1:9195:9195 \
7878
apache/shenyu-bootstrap:latest
7979
```
8080

81+
Local management controllers are registered only when `SHENYU_LOCAL_ENABLED=true`; omitting it disables the controllers and their dispatch filter together.
82+
8183
Admin listens on `http://localhost:9095`; the gateway listens on `http://localhost:9195`. Wait for both services to start, then check their health endpoints:
8284

8385
```bash

‎shenyu-bootstrap/src/main/resources/application.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,7 @@ shenyu:
365365
# max-response-bytes: 0
366366
# rate-limiter.enabled: false
367367
local:
368+
# Local management controllers and the dispatch filter are registered only with an explicit true.
368369
enabled: false
369370
sha512Key: "BA3253876AED6BC22D4A6FF53D8406C6AD864195ED144AB5C87621B6C233B548BAEAE6956DF346EC8C17F5EA10F35EE3CBC514797ED7DDD3145464E2A0BAB413"
370371
websocket:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
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.plugin.wasm.base.gateway;
19+
20+
import org.apache.shenyu.common.constant.Constants;
21+
import org.apache.shenyu.plugin.base.cache.BaseDataCache;
22+
import org.junit.jupiter.api.BeforeEach;
23+
import org.junit.jupiter.api.Test;
24+
import org.springframework.boot.test.context.SpringBootTest;
25+
import org.springframework.boot.test.web.server.LocalServerPort;
26+
import org.springframework.http.MediaType;
27+
import org.springframework.test.web.reactive.server.WebTestClient;
28+
29+
import java.time.Duration;
30+
31+
import static org.junit.jupiter.api.Assertions.assertNotNull;
32+
33+
/**
34+
* Verifies that explicit local management enablement keeps the production
35+
* dispatch path and its key check, even when health dispatch matches every path.
36+
*/
37+
@SpringBootTest(classes = WasmGatewayTest.GatewayApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
38+
properties = {"spring.main.web-application-type=reactive", "spring.main.allow-bean-definition-overriding=true",
39+
"shenyu.local.enabled=true",
40+
"shenyu.local.sha512Key=BA3253876AED6BC22D4A6FF53D8406C6AD864195ED144AB5C87621B6C233B548BAEAE6956DF346EC8C17F5EA10F35EE3CBC514797ED7DDD3145464E2A0BAB413",
41+
"shenyu.health.enabled=true", "shenyu.health.paths=/", "shenyu.alert.enabled=false"})
42+
final class LocalManagementDispatchTest {
43+
44+
private static final String LOCAL_KEY = "123456";
45+
46+
private static final String PLUGIN_BODY = "{\"id\":\"local-gate-plugin\",\"name\":\"local-gate\",\"enabled\":true}";
47+
48+
@LocalServerPort
49+
private int port;
50+
51+
private WebTestClient client;
52+
53+
@BeforeEach
54+
void setUp() {
55+
client = WebTestClient.bindToServer().baseUrl("http://localhost:" + port)
56+
.responseTimeout(Duration.ofSeconds(15)).build();
57+
BaseDataCache.getInstance().cleanPluginData();
58+
}
59+
60+
@Test
61+
void missingKeyIsRejected() {
62+
client.post().uri("/shenyu/plugin/saveOrUpdate")
63+
.contentType(MediaType.APPLICATION_JSON)
64+
.bodyValue(PLUGIN_BODY)
65+
.exchange()
66+
.expectStatus().isForbidden();
67+
}
68+
69+
@Test
70+
void correctKeyReachesTheLocalController() {
71+
client.post().uri("/shenyu/plugin/saveOrUpdate")
72+
.header(Constants.LOCAL_KEY, LOCAL_KEY)
73+
.contentType(MediaType.APPLICATION_JSON)
74+
.bodyValue(PLUGIN_BODY)
75+
.exchange()
76+
.expectStatus().isOk();
77+
assertNotNull(BaseDataCache.getInstance().obtainPluginData("local-gate"));
78+
}
79+
}

‎shenyu-spring-boot-starter/shenyu-spring-boot-starter-gateway/src/main/java/org/apache/shenyu/springboot/starter/gateway/ShenyuConfiguration.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ public WebFilter collapseSlashesFilter() {
181181
*/
182182
@Bean
183183
@Order(-200)
184-
@ConditionalOnProperty(name = "shenyu.local.enabled", havingValue = "true", matchIfMissing = true)
184+
@ConditionalOnProperty(name = "shenyu.local.enabled", havingValue = "true", matchIfMissing = false)
185185
public WebFilter localDispatcherFilter(final DispatcherHandler dispatcherHandler, final ShenyuConfig shenyuConfig) {
186186
return new LocalDispatcherFilter(dispatcherHandler, shenyuConfig.getLocal().getSha512Key());
187187
}

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

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@
2121
import org.apache.shenyu.plugin.api.RemoteAddressResolver;
2222
import org.apache.shenyu.plugin.api.result.ShenyuResult;
2323
import org.apache.shenyu.sync.data.api.PluginDataSubscriber;
24+
import org.apache.shenyu.web.controller.LocalAppAuthController;
25+
import org.apache.shenyu.web.controller.LocalMetadataController;
26+
import org.apache.shenyu.web.controller.LocalPluginController;
27+
import org.apache.shenyu.web.filter.LocalDispatcherFilter;
2428
import org.apache.shenyu.web.handler.ShenyuWebHandler;
2529
import org.apache.shenyu.web.loader.ShenyuLoaderService;
2630
import org.junit.jupiter.api.BeforeEach;
@@ -31,6 +35,7 @@
3135
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
3236
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
3337
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
38+
import org.springframework.context.ApplicationContext;
3439
import org.springframework.context.annotation.Bean;
3540
import org.springframework.context.annotation.Configuration;
3641
import org.springframework.http.codec.support.DefaultServerCodecConfigurer;
@@ -39,6 +44,7 @@
3944

4045
import static org.junit.jupiter.api.Assertions.assertEquals;
4146
import static org.junit.jupiter.api.Assertions.assertNotNull;
47+
import static org.junit.jupiter.api.Assertions.assertTrue;
4248

4349
/**
4450
* Test case for {@link ShenyuConfiguration}.
@@ -51,7 +57,11 @@ public class ShenyuConfigurationTest {
5157

5258
@BeforeEach
5359
public void before() {
54-
applicationContextRunner = new ApplicationContextRunner()
60+
applicationContextRunner = baseRunner().withPropertyValues("shenyu.local.enabled=true");
61+
}
62+
63+
private ApplicationContextRunner baseRunner() {
64+
return new ApplicationContextRunner()
5565
.withConfiguration(AutoConfigurations.of(ShenyuConfiguration.class))
5666
.withBean(ShenyuConfigurationTest.class)
5767
.withBean(DefaultServerCodecConfigurer.class)
@@ -61,11 +71,29 @@ public void before() {
6171
"debug=true",
6272
"shenyu.cross.enabled=true",
6373
"shenyu.file.enabled=true",
64-
"shenyu.exclude.enabled=true",
65-
"shenyu.local.enabled=true"
74+
"shenyu.exclude.enabled=true"
6675
);
6776
}
6877

78+
@Test
79+
public void testLocalManagementRequiresExplicitEnablement() {
80+
baseRunner().run(context -> assertNoLocalManagement(context));
81+
baseRunner().withPropertyValues("shenyu.local.enabled=false").run(context -> assertNoLocalManagement(context));
82+
baseRunner().withPropertyValues("shenyu.local.enabled=true").run(context -> {
83+
assertTrue(context.getBeansOfType(LocalDispatcherFilter.class).size() == 1);
84+
assertTrue(context.getBeansOfType(LocalPluginController.class).size() == 1);
85+
assertTrue(context.getBeansOfType(LocalMetadataController.class).size() == 1);
86+
assertTrue(context.getBeansOfType(LocalAppAuthController.class).size() == 1);
87+
});
88+
}
89+
90+
private void assertNoLocalManagement(final ApplicationContext context) {
91+
assertTrue(context.getBeansOfType(LocalDispatcherFilter.class).isEmpty());
92+
assertTrue(context.getBeansOfType(LocalPluginController.class).isEmpty());
93+
assertTrue(context.getBeansOfType(LocalMetadataController.class).isEmpty());
94+
assertTrue(context.getBeansOfType(LocalAppAuthController.class).isEmpty());
95+
}
96+
6997
@Test
7098
public void testShenyuWebHandler() {
7199
applicationContextRunner.run(context -> {

‎shenyu-spring-boot-starter/shenyu-spring-boot-starter-sync-data-center/shenyu-spring-boot-starter-sync-data-file/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ A Boot environment post-processor establishes ownership before auto-configuratio
5656

5757
* The shipped `ws://localhost:9095/websocket` default is explicitly suppressed. Other configured WebSocket/HTTP/ZooKeeper/Nacos/etcd/Apollo sync endpoints fail startup; remove them when selecting file mode. Missing, blank and `false` endpoint properties mean disabled. The reserved shipped WebSocket URL is suppressed even when explicitly supplied.
5858
* Admin heartbeat, WebSocket initial-sync readiness and external-JAR plugin loading are disabled in file mode, including inherited Bootstrap defaults. Their normal settings are retained when file mode is disabled.
59-
* Local management API dispatch is disabled, including its implicit default. Explicit `shenyu.local.enabled=true`, `shenyu.register.enabled=true` and `shenyu.alert.enabled=true` fail startup as conflicting writers/Admin clients. No HTTP management key is needed.
59+
* Local management controllers and their dispatch filter share one explicit gate: `shenyu.local.enabled=true`. Omitting the property disables both (previously the filter was implicitly enabled and failed closed without a key). Explicit `shenyu.local.enabled=true`, `shenyu.register.enabled=true` and `shenyu.alert.enabled=true` fail startup as conflicting writers/Admin clients. No HTTP management key is needed.
6060
* All configuration is parsed and validated before any entry is applied. Plugins, selectors, rules and upstreams are then applied in dependency order. Undeclared classpath plugins are disabled without initializing their configuration handlers.
6161
* Application runs after singleton initialization and before the web server lifecycle starts. Registered asynchronous handler work must finish within `shenyu.sync.file.apply-timeout` (default `30s`, maximum `5m`). Missing/invalid files, handler failures and timeouts abort startup. A file-mode WebFilter additionally refuses traffic with 503 until application succeeds. Spring publishes normal accepting-traffic readiness only after successful startup; no Admin readiness check is installed.
6262
* Shutdown and startup failure remove file-owned entries through the subscribers. Restarting the same file preserves explicit IDs and replaces cache entries rather than adding generated identities.

‎shenyu-spring-boot-starter/shenyu-spring-boot-starter-sync-data-center/shenyu-spring-boot-starter-sync-data-file/src/test/java/org/apache/shenyu/springboot/starter/sync/data/file/FileModeIntegrationTest.java‎

Lines changed: 36 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@
2424
import org.apache.shenyu.common.config.ShenyuConfig;
2525
import org.apache.shenyu.common.utils.InitialSyncApplication;
2626
import org.apache.shenyu.sync.data.api.SyncDataService;
27+
import org.apache.shenyu.web.controller.LocalAppAuthController;
28+
import org.apache.shenyu.web.controller.LocalMetadataController;
29+
import org.apache.shenyu.web.controller.LocalPluginController;
2730
import org.apache.shenyu.web.filter.LocalDispatcherFilter;
2831
import org.apache.shenyu.web.handler.ShenyuWebHandler;
2932
import org.junit.jupiter.api.Test;
@@ -36,6 +39,7 @@
3639
import org.springframework.boot.availability.ReadinessState;
3740
import org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext;
3841
import org.springframework.context.ConfigurableApplicationContext;
42+
import org.springframework.http.MediaType;
3943
import org.springframework.web.reactive.function.client.WebClient;
4044
import reactor.core.publisher.Mono;
4145
import reactor.netty.DisposableServer;
@@ -63,19 +67,20 @@ class FileModeIntegrationTest {
6367
private boolean failApplication;
6468

6569
private ConfigurableApplicationContext start(final Path path, final String... additional) {
66-
String[] args = new String[additional.length + 7];
70+
boolean explicitPort = Arrays.stream(additional).anyMatch(argument -> argument.startsWith("--server.port="));
71+
String[] args = new String[additional.length + (explicitPort ? 6 : 7)];
6772
args[0] = "--spring.config.location=classpath:bootstrap-defaults/application.yml";
6873
args[1] = "--shenyu.sync.file.enabled=true";
6974
args[2] = "--shenyu.sync.file.path=" + path;
70-
args[3] = "--server.port=0";
71-
args[4] = "--spring.main.banner-mode=off";
72-
args[5] = "--shenyu.sync.websocket.initial-sync-readiness=true";
73-
args[6] = "--management.endpoint.health.probes.enabled=true";
74-
System.arraycopy(additional, 0, args, 7, additional.length);
75-
ArrayList<String> arguments = new ArrayList<>(Arrays.asList(args));
76-
if (additional.length > 0) {
77-
arguments.remove("--server.port=0");
75+
int index = 3;
76+
if (!explicitPort) {
77+
args[index++] = "--server.port=0";
7878
}
79+
args[index++] = "--spring.main.banner-mode=off";
80+
args[index++] = "--shenyu.sync.websocket.initial-sync-readiness=true";
81+
args[index++] = "--management.endpoint.health.probes.enabled=true";
82+
System.arraycopy(additional, 0, args, index, additional.length);
83+
ArrayList<String> arguments = new ArrayList<>(Arrays.asList(args));
7984
SpringApplication application = new SpringApplication(TestApplication.class);
8085
if (failApplication) {
8186
application.addInitializers(context -> context.getBeanFactory().addBeanPostProcessor(new BeanPostProcessor() {
@@ -140,6 +145,28 @@ void forwardsAndRestartsWithoutAdminOrMutableLocalApis() throws IOException {
140145
}
141146
}
142147

148+
@Test
149+
void broadHealthPrefixCannotReachDisabledLocalWriters() throws IOException {
150+
Path path = directory.resolve("gateway.yaml");
151+
Files.writeString(path, FileConfigurationParserTest.document().toString());
152+
try (ConfigurableApplicationContext context = start(path, "--shenyu.health.paths=/")) {
153+
int port = ((ReactiveWebServerApplicationContext) context).getWebServer().getPort();
154+
WebClient client = WebClient.create("http://127.0.0.1:" + port);
155+
String result = client.post().uri("/shenyu/plugin/rule/saveOrUpdate")
156+
.contentType(MediaType.APPLICATION_JSON)
157+
.bodyValue("{\"id\":\"injected-rule\",\"selectorId\":\"http-api\",\"pluginName\":\"divide\"}")
158+
.exchangeToMono(response -> response.bodyToMono(String.class).defaultIfEmpty("")
159+
.map(body -> response.statusCode().value() + "|" + body))
160+
.block(Duration.ofSeconds(10));
161+
assertThat(result).startsWith("404|");
162+
assertThat(BaseDataCache.getInstance().obtainRuleData("http-api")).hasSize(1);
163+
assertThat(context.getBeansOfType(LocalDispatcherFilter.class)).isEmpty();
164+
assertThat(context.getBeansOfType(LocalPluginController.class)).isEmpty();
165+
assertThat(context.getBeansOfType(LocalMetadataController.class)).isEmpty();
166+
assertThat(context.getBeansOfType(LocalAppAuthController.class)).isEmpty();
167+
}
168+
}
169+
143170
@Test
144171
void invalidConfigurationCannotStartListening() throws IOException {
145172
Path path = directory.resolve("invalid.yaml");

‎shenyu-web/src/main/java/org/apache/shenyu/web/controller/LocalAppAuthController.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import org.slf4j.Logger;
2525
import org.slf4j.LoggerFactory;
2626
import org.springframework.beans.factory.ObjectProvider;
27+
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
2728
import org.springframework.http.MediaType;
2829
import org.springframework.web.bind.annotation.GetMapping;
2930
import org.springframework.web.bind.annotation.PostMapping;
@@ -40,6 +41,7 @@
4041
* The type AppAuth controller.
4142
*/
4243
@RestController
44+
@ConditionalOnProperty(name = "shenyu.local.enabled", havingValue = "true", matchIfMissing = false)
4345
@RequestMapping(value = "/shenyu", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
4446
public class LocalAppAuthController {
4547

‎shenyu-web/src/main/java/org/apache/shenyu/web/controller/LocalMetadataController.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import org.slf4j.Logger;
2525
import org.slf4j.LoggerFactory;
2626
import org.springframework.beans.factory.ObjectProvider;
27+
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
2728
import org.springframework.http.MediaType;
2829
import org.springframework.web.bind.annotation.GetMapping;
2930
import org.springframework.web.bind.annotation.PostMapping;
@@ -40,6 +41,7 @@
4041
* The type Meta data controller.
4142
*/
4243
@RestController
44+
@ConditionalOnProperty(name = "shenyu.local.enabled", havingValue = "true", matchIfMissing = false)
4345
@RequestMapping(value = "/shenyu", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
4446
public class LocalMetadataController {
4547

‎shenyu-web/src/main/java/org/apache/shenyu/web/controller/LocalPluginController.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
import org.apache.shenyu.sync.data.api.PluginDataSubscriber;
4141
import org.slf4j.Logger;
4242
import org.slf4j.LoggerFactory;
43+
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
4344
import org.springframework.http.MediaType;
4445
import org.springframework.web.bind.annotation.GetMapping;
4546
import org.springframework.web.bind.annotation.PostMapping;
@@ -61,6 +62,7 @@
6162
* The type Plugin controller.
6263
*/
6364
@RestController
65+
@ConditionalOnProperty(name = "shenyu.local.enabled", havingValue = "true", matchIfMissing = false)
6466
@RequestMapping(value = "/shenyu", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
6567
public class LocalPluginController {
6668

0 commit comments

Comments
 (0)