Skip to content

Commit dabe7ee

Browse files
authored
[ISSUE #8200] Add scoped configuration contracts and shared validation providers (#8274)
* feat(config): add scoped plugin configuration contracts (#8200) * test(admin): deduplicate import after upstream plugin-event changes * fix(common): normalize absent configuration enum values Propagate the same optional-enumeration correction reviewed for #8279 into this prerequisite branch. Null enum metadata means unrestricted; non-null lists retain defensive copying and null-entry rejection. Add regression tests adapted to this branch's Field constructors. Validation: actual production classes compiled with Java 21, standalone constructor/copy/immutability/null-element checks pass; git diff --check passes. Local Maven/JUnit/Checkstyle/RAT remain blocked by wrapper DNS failure for repo.maven.apache.org. Hosted exact-head CI checked separately.
1 parent c5ff59f commit dabe7ee

18 files changed

Lines changed: 1011 additions & 10 deletions

File tree

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
<!--
2+
Licensed to the Apache Software Foundation (ASF) under one
3+
or more contributor license agreements. See the NOTICE file
4+
distributed with this work for additional information
5+
regarding copyright ownership. The ASF licenses this file
6+
to you under the Apache License, Version 2.0 (the
7+
"License"); you may not use this file except in compliance
8+
with the License. You may obtain a copy of the License at
9+
10+
http://www.apache.org/licenses/LICENSE-2.0
11+
12+
Unless required by applicable law or agreed to in writing,
13+
software distributed under the License is distributed on an
14+
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
KIND, either express or implied. See the License for the
16+
specific language governing permissions and limitations
17+
under the License.
18+
-->
19+
20+
# Optional plugin configuration contracts
21+
22+
`shenyu-common` provides `ConfigurationContractProvider` and
23+
`ConfigurationContractRegistry`. A contract is keyed by the stable plugin name,
24+
one existing storage scope (`PLUGIN`, `SELECTOR`, `RULE`), and a contract version.
25+
It does not change `PluginData.config`, selector/rule handle strings, plugin
26+
names, synchronization envelopes, or the existing `PluginHandle` form metadata.
27+
Its version is not a fleet configuration revision.
28+
29+
## Registration and inspection
30+
31+
Put a pure provider in a lightweight shared contract artifact and register its
32+
class in `META-INF/services/org.apache.shenyu.common.config.contract.ConfigurationContractProvider`.
33+
The shared registry discovers these providers with Java ServiceLoader from the
34+
contract API's classloader. Applications can also register trusted providers
35+
explicitly during startup. It rejects duplicate plugin/scope/version keys and
36+
limits the catalog to 1024 registrations. Provider construction and validation
37+
must not initialize a request plugin, an SDK client, perform remote calls, or
38+
modify configuration/caches. This is a trusted extension contract, not a Java
39+
sandbox. Admin must install the lightweight artifact, never a gateway plugin JAR
40+
or its SDK implementation to obtain a validator.
41+
42+
`registry.catalog()` returns immutable, deterministically ordered metadata.
43+
Admin exposes the same catalog at `GET /plugin-template/config-contracts`, using
44+
the existing `system:plugin:edit` permission. It contains field descriptions and
45+
effective defaults, never configured values. Existing form metadata remains
46+
available for unconverted plugins and forms; the endpoint does not generate or
47+
replace forms.
48+
49+
```java
50+
ConfigurationValidation result = ConfigurationContractRegistry.shared()
51+
.validate("agentGateway", ConfigurationScope.PLUGIN, "1", originalJson);
52+
```
53+
54+
Treat `VALID`, `INVALID`, `UNREGISTERED`, and `UNSUPPORTED_VERSION` distinctly.
55+
`UNREGISTERED` preserves the legacy path but is not a validation/readiness claim.
56+
An explicitly unsupported version requires an availability/compatibility
57+
decision, never implicit success. The existing versionless production adapter
58+
selects version `1`; introducing another wire/version-selection policy needs a
59+
separate compatibility change. A provider may be installed without capability
60+
descriptors, a graph executor or the reactive test kit.
61+
62+
## Structural checks and semantics
63+
64+
Field descriptors record JSON type, required/null behavior, effective default,
65+
unit, sensitivity, optional inclusive numeric bounds and optional closed string
66+
enumerations. SPI names must not be turned into closed built-in enums.
67+
`structuralValidation=true` opts into strict JSON syntax/duplicate/trailing-token
68+
checks, declared field types, required/null checks, integral/range constraints,
69+
and enumerations. Dotted declared paths can describe nested object fields;
70+
unknown-field rejection currently applies to the root object's names. Nested
71+
unknown-field policy and cross-field rules belong to the semantic provider.
72+
Defaults describe execution and are never inserted into stored input.
73+
74+
`structuralValidation=false` leaves coercion, syntax and null compatibility to
75+
the adopted existing parser. `UnknownFields` explicitly describes allow,
76+
root-level reject, or semantic-validator ownership. This lets a legacy parser
77+
keep its accepted input set without globally making other plugins strict.
78+
Custom semantic checks run after successful optional structural checks. They
79+
return stable `ConfigurationViolation` codes and declared paths, not exception
80+
messages or configuration values. Errors are capped at 16; paths at 128
81+
characters. Parser/provider exceptions become `PROVIDER_FAILURE` without their
82+
message/cause. Unknown supplied field names are reported at `$`, so a secret
83+
used as a key cannot leak through diagnostics. Sensitivity is descriptive
84+
metadata for tooling, not permission to expose other configured values.
85+
86+
Runtime dictionary/SPI, credential and endpoint availability remain binding
87+
checks. `RUNTIME_BINDING_UNAVAILABLE` is a separate diagnostic code available
88+
to adapters. A successful shared schema/semantic check does not establish that
89+
an extension or credential exists on a particular gateway, that resources were
90+
prepared, or that a candidate became active.
91+
92+
## Operation ownership and initial production adapter
93+
94+
Validation returns facts and never clears, retains, replaces or deletes a cache.
95+
Each descriptor documents operation semantics; the owning data handler continues
96+
to implement them. Missing input, explicit JSON null, blank clearing, `{}`,
97+
invalid update, disable and removal are separate cases. Do not copy another
98+
plugin's clearing or eviction policy merely because both use this registry.
99+
100+
The first production adapter delegates Agent Gateway plugin configuration to
101+
its existing `AgentGatewayAggregationConfig.parsePluginConfig` implementation.
102+
Missing/blank/empty-object input keeps local-only behavior. Literal JSON null,
103+
unknown fields and malformed aggregation objects remain invalid. The generic
104+
Admin validation entry uses the registry for create/update/import, including
105+
persisted plugin identity on update. Gateway catalog reload validates before
106+
credential resolution/resource preparation and then retains its existing parser
107+
and lifecycle. Invalid candidates leave the previous directory active; removal
108+
and disable remain lifecycle operations. No request-path work is added.
109+
110+
`META-INF/shenyu/config-contract-fixtures/agentGateway-plugin-v1.tsv` is the
111+
versioned fixture corpus packaged with the contract artifact. The common parser/
112+
registry, Admin validator, and real gateway catalog-reload tests consume it.
113+
`@missing` and `@blank` distinguish missing values from literal JSON null.
114+
Production service tests also check invalid create, persisted-identity update
115+
and import rejection before writes/events. Generic fixtures exercise all three
116+
scopes, defaults/units, type/range/enum/null policies, immutable metadata,
117+
duplicates, unknown versions, legacy fallback and bounded secret-free failures.
118+
119+
Use the repository Maven wrapper to run the focused reactor:
120+
121+
```text
122+
./mvnw -B -ntp -pl shenyu-admin,shenyu-plugin/shenyu-plugin-agent-gateway -am verify -Dtest=ConfigurationContractRegistryTest,AgentGatewayAggregationConfigTest,AgentGatewayPluginConfigValidatorTest,PluginServiceTest,PluginControllerTest,ManagedRemoteMcpCatalogTest,HttpLongPollingDataChangedListenerTest -Dsurefire.failIfNoSpecifiedTests=false -Djacoco.skip=true -DskipRemoteResources=true -Dmaven.javadoc.skip=true
123+
```

‎shenyu-admin/src/main/java/org/apache/shenyu/admin/controller/PluginController.java‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import org.apache.shenyu.admin.utils.ShenyuResultMessage;
3535
import org.apache.shenyu.admin.validation.annotation.Existed;
3636
import org.apache.shenyu.common.dto.PluginData;
37+
import org.apache.shenyu.common.config.contract.ConfigurationContractRegistry;
3738
import org.apache.shiro.authz.annotation.RequiresPermissions;
3839
import org.springframework.web.bind.annotation.DeleteMapping;
3940
import org.springframework.web.bind.annotation.GetMapping;
@@ -89,6 +90,16 @@ public ShenyuAdminResult queryAllPlugins() {
8990
List<PluginData> pluginDataList = pluginService.listAll();
9091
return ShenyuAdminResult.success(ShenyuResultMessage.QUERY_SUCCESS, pluginDataList);
9192
}
93+
94+
/**
95+
* Inspect installed lightweight configuration contracts without loading plugin implementations.
96+
* @return registered contract metadata, excluding configuration values
97+
*/
98+
@GetMapping("/config-contracts")
99+
@RequiresPermissions("system:plugin:edit")
100+
public ShenyuAdminResult configurationContracts() {
101+
return ShenyuAdminResult.success(ShenyuResultMessage.QUERY_SUCCESS, ConfigurationContractRegistry.shared().catalog());
102+
}
92103

93104
/**
94105
* detail plugin.

‎shenyu-admin/src/main/java/org/apache/shenyu/admin/validation/validator/AgentGatewayPluginConfigValidator.java‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,27 +18,25 @@
1818
package org.apache.shenyu.admin.validation.validator;
1919

2020
import org.apache.shenyu.admin.exception.ShenyuAdminException;
21-
import org.apache.shenyu.common.dto.AgentGatewayAggregationConfig;
22-
import org.apache.shenyu.common.enums.PluginEnum;
21+
import org.apache.shenyu.common.config.contract.ConfigurationContractRegistry;
22+
import org.apache.shenyu.common.config.contract.ConfigurationScope;
23+
import org.apache.shenyu.common.config.contract.ConfigurationValidation;
2324

24-
/** Reject invalid aggregation references before persistence and data-sync publication. */
25+
/** Registry-backed plugin-scope validation retaining the existing public entry point. */
2526
public final class AgentGatewayPluginConfigValidator {
2627

2728
private AgentGatewayPluginConfigValidator() {
2829
}
2930

3031
/**
31-
* Leave other plugins' configuration contracts unchanged.
32+
* Validate registered contracts and preserve the unregistered legacy path.
3233
* @param name trusted stored plugin name
3334
* @param config supplied plugin configuration
3435
*/
3536
public static void validate(final String name, final String config) {
36-
if (PluginEnum.AGENT_GATEWAY.getName().equals(name)) {
37-
try {
38-
AgentGatewayAggregationConfig.parsePluginConfig(config);
39-
} catch (IllegalArgumentException error) {
40-
throw new ShenyuAdminException("Invalid Agent Gateway aggregation configuration");
41-
}
37+
ConfigurationValidation result = ConfigurationContractRegistry.shared().validate(name, ConfigurationScope.PLUGIN, "1", config);
38+
if (result.status() == ConfigurationValidation.Status.INVALID) {
39+
throw new ShenyuAdminException("Invalid plugin configuration: " + result.plugin() + " " + result.violations().get(0).code());
4240
}
4341
}
4442
}

‎shenyu-admin/src/test/java/org/apache/shenyu/admin/controller/PluginControllerTest.java‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
import static org.mockito.BDDMockito.given;
6262
import static org.mockito.Mockito.mock;
6363
import static org.mockito.Mockito.when;
64+
import static org.mockito.Mockito.verifyNoInteractions;
6465
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
6566
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
6667

@@ -124,6 +125,16 @@ public void testQueryPlugins() throws Exception {
124125
.andReturn();
125126
}
126127

128+
@Test
129+
public void testConfigurationContractsAreMetadataOnly() throws Exception {
130+
mockMvc.perform(MockMvcRequestBuilders.get("/plugin-template/config-contracts"))
131+
.andExpect(status().isOk())
132+
.andExpect(jsonPath("$.data[0].plugin", is("agentGateway")))
133+
.andExpect(jsonPath("$.data[0].scope", is("PLUGIN")))
134+
.andExpect(jsonPath("$.data[0].version", is("1")));
135+
verifyNoInteractions(pluginService);
136+
}
137+
127138
@Test
128139
public void testSearchPluginsOmitsJarField() throws Exception {
129140
PluginListVO summary = new PluginListVO();

‎shenyu-admin/src/test/java/org/apache/shenyu/admin/service/PluginServiceTest.java‎

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

2020
import org.apache.commons.lang3.StringUtils;
21+
import org.apache.shenyu.admin.exception.ShenyuAdminException;
2122
import org.apache.shenyu.admin.mapper.NamespacePluginRelMapper;
2223
import org.apache.shenyu.admin.mapper.PluginMapper;
2324
import org.apache.shenyu.admin.mapper.SelectorMapper;
@@ -60,11 +61,14 @@
6061
import static org.hamcrest.Matchers.equalTo;
6162
import static org.junit.jupiter.api.Assertions.assertEquals;
6263
import static org.junit.jupiter.api.Assertions.assertNotNull;
64+
import static org.junit.jupiter.api.Assertions.assertThrows;
6365
import static org.mockito.ArgumentMatchers.any;
6466
import static org.mockito.ArgumentMatchers.eq;
6567
import static org.mockito.BDDMockito.given;
6668
import static org.mockito.Mockito.verify;
6769
import static org.mockito.Mockito.when;
70+
import static org.mockito.Mockito.never;
71+
import static org.mockito.Mockito.verifyNoInteractions;
6872

6973
/**
7074
* Test cases for PluginService.
@@ -207,6 +211,40 @@ public void testImportData() {
207211

208212
}
209213

214+
@Test
215+
public void invalidRegisteredPluginCreateIsRejectedBeforePersistence() {
216+
PluginDTO candidate = new PluginDTO();
217+
candidate.setName("agentGateway");
218+
candidate.setConfig("{\"SECRET\":\"value\"}");
219+
assertThrows(ShenyuAdminException.class, () -> pluginService.createOrUpdate(candidate));
220+
verifyNoInteractions(pluginMapper, modelDataEventPublisher);
221+
}
222+
223+
@Test
224+
public void registeredPluginUpdateUsesPersistedIdentityBeforePersistence() {
225+
PluginDTO candidate = new PluginDTO();
226+
candidate.setId("existing");
227+
candidate.setName("legacy");
228+
candidate.setConfig("{\"SECRET\":\"value\"}");
229+
PluginDO stored = new PluginDO();
230+
stored.setName("agentGateway");
231+
when(pluginMapper.selectById("existing")).thenReturn(stored);
232+
assertThrows(ShenyuAdminException.class, () -> pluginService.createOrUpdate(candidate));
233+
verify(pluginMapper, never()).updateSelective(any());
234+
verifyNoInteractions(modelDataEventPublisher);
235+
}
236+
237+
@Test
238+
public void invalidRegisteredPluginImportIsRejectedBeforePersistence() {
239+
PluginDTO candidate = new PluginDTO();
240+
candidate.setName("agentGateway");
241+
candidate.setConfig("{\"SECRET\":\"value\"}");
242+
when(pluginMapper.selectAll()).thenReturn(Collections.emptyList());
243+
assertThrows(ShenyuAdminException.class, () -> pluginService.importData(Collections.singletonList(candidate), null));
244+
verify(pluginMapper, never()).insertSelective(any());
245+
verifyNoInteractions(modelDataEventPublisher);
246+
}
247+
210248
private void publishEvent() {
211249
PluginDO pluginDO = buildPluginDO();
212250
given(this.pluginMapper.selectById("123")).willReturn(pluginDO);

‎shenyu-admin/src/test/java/org/apache/shenyu/admin/validation/validator/AgentGatewayPluginConfigValidatorTest.java‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,36 @@
2020
import org.apache.shenyu.admin.exception.ShenyuAdminException;
2121
import org.junit.jupiter.params.ParameterizedTest;
2222
import org.junit.jupiter.params.provider.ValueSource;
23+
import org.junit.jupiter.params.provider.MethodSource;
2324

2425
import static org.junit.jupiter.api.Assertions.assertThrows;
2526
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
2627

2728
class AgentGatewayPluginConfigValidatorTest {
2829

30+
@ParameterizedTest(name = "{0}")
31+
@MethodSource("configurationFixtures")
32+
void validatesSharedContractFixtures(final String name, final boolean accepted, final String source) {
33+
if (accepted) {
34+
assertDoesNotThrow(() -> AgentGatewayPluginConfigValidator.validate("agentGateway", source));
35+
} else {
36+
assertThrows(ShenyuAdminException.class, () -> AgentGatewayPluginConfigValidator.validate("agentGateway", source));
37+
}
38+
}
39+
40+
private static java.util.stream.Stream<org.junit.jupiter.params.provider.Arguments> configurationFixtures() throws java.io.IOException {
41+
try (var input = java.util.Objects.requireNonNull(AgentGatewayPluginConfigValidatorTest.class.getResourceAsStream(
42+
"/META-INF/shenyu/config-contract-fixtures/agentGateway-plugin-v1.tsv"));
43+
var reader = new java.io.BufferedReader(new java.io.InputStreamReader(input, java.nio.charset.StandardCharsets.UTF_8))) {
44+
return reader.lines().filter(line -> !line.isBlank() && !line.startsWith("#")).map(line -> {
45+
String[] fields = line.split("\\t", 3);
46+
String source = "@missing".equals(fields[2]) ? null : "@blank".equals(fields[2]) ? "" : fields[2];
47+
return org.junit.jupiter.params.provider.Arguments.of(fields[0], Boolean.parseBoolean(fields[1]), source);
48+
}).toList().stream();
49+
}
50+
}
51+
52+
2953
@ParameterizedTest
3054
@ValueSource(strings = {"{}", "", "{\"aggregation\":{\"revision\":\"clear\",\"servers\":[]}}"})
3155
void acceptsExplicitLocalOnlyConfiguration(final String source) {
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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.common.config.contract;
19+
20+
import org.apache.shenyu.common.dto.AgentGatewayAggregationConfig;
21+
22+
import java.util.List;
23+
import java.util.Map;
24+
25+
/** Behavior-preserving adapter for the existing shared Agent Gateway aggregation parser. */
26+
public final class AgentGatewayPluginContract implements ConfigurationContractProvider {
27+
28+
private static final ConfigurationContract CONTRACT = new ConfigurationContract("agentGateway", ConfigurationScope.PLUGIN, "1", false,
29+
ConfigurationContract.UnknownFields.SEMANTIC_VALIDATOR,
30+
Map.of("aggregation", new ConfigurationContract.Field(ConfigurationContract.Type.OBJECT, false, false,
31+
"local-only when missing/blank/empty object", "", false, null, null, List.of())),
32+
Map.of("missing", "local-only", "blank", "local-only", "emptyObject", "local-only", "explicitNull", "invalid",
33+
"invalidUpdate", "reject before persistence/preparation; retain current remote catalog", "remove", "owned by catalog lifecycle"));
34+
35+
@Override
36+
public ConfigurationContract contract() {
37+
return CONTRACT;
38+
}
39+
40+
@Override
41+
public List<ConfigurationViolation> validateSemantic(final String source) {
42+
try {
43+
AgentGatewayAggregationConfig.parsePluginConfig(source);
44+
return List.of();
45+
} catch (IllegalArgumentException error) {
46+
return List.of(new ConfigurationViolation("$", ConfigurationViolation.Code.SEMANTIC_INVALID));
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)