diff --git a/docs/divide-configuration-contract.md b/docs/divide-configuration-contract.md new file mode 100644 index 000000000000..c751e3a3b688 --- /dev/null +++ b/docs/divide-configuration-contract.md @@ -0,0 +1,130 @@ + + +# Divide rule configuration, contract version 1 + +`DivideRuleContract` registers the existing HTTP routing rule handle with the +shared registry. It inventories every current root, Canary, predicate, sticky-key +and session-affinity DTO field. It does not invent plugin or selector scopes, +change JSON storage, construct SDK clients, or change routing/response ownership. +The machine-readable catalog is also available through Admin's existing +`/plugin-template/config-contracts` metadata API. + +| Root field | Omitted-field default | Units / interpretation | +| --- | --- | --- | +| `loadBalance` | `random` | Open SPI name, including external implementations | +| `retryStrategy` | `current` | Existing retry strategy selection | +| `retryBackOffSpec` | `default` | Existing default/fixed/exponential interpretation and fallback | +| `retry` | 3 | Retry count | +| `timeout` | 3000 | Milliseconds | +| `requestTimeout` | absent | Overall HTTPRoute request budget in milliseconds. An absent value uses legacy timeout handling. Zero disables the deadline. | +| `headerMaxSize` | 0 | UTF-8 bytes plus framing allowance; non-positive disables this check | +| `requestMaxSize` | 0 | Body bytes; non-positive disables enforcement | +| `poolGroup` | absent | Optional [upstream connection-pool group](upstream-pool-groups.md). An absent or empty value uses the shared default pool. Named groups are resolved by the gateway. | +| `canary` | absent | Legacy routing; a present configuration uses existing partition validation | +| `sticky` | absent | Existing optional HTTP affinity | + +Defaults are descriptive and never inserted into stored JSON. Gson's existing +root-field coercion, explicit-null and unknown-field behavior remains in force. +For primitive fields, explicit null retains the initializer; reference fields can +remain null. This version adds no universal positive-range rule for legacy root +fields and no closed built-in allowlist for extension names. A descriptor does +not prove an extension is installed. + +## Nested fields + +| Field group | Current meaning / default | +| --- | --- | +| `canary.enabled` | false selects Stable; present value must be a JSON boolean | +| `canary.conditions` | Optional array; empty allows participation; explicit null is invalid | +| `canary.conditions[].paramType`, `.operator` | Existing ParameterData and PredicateJudge SPI names | +| `canary.conditions[].paramName`, `.paramValue` | Existing source/operator-specific requirements, including regex/time applicability | +| `canary.matchMode` | 0 AND; 1 OR; no fractional/string/null coercion | +| `canary.percentage` | 0, range 0..100; same existing strict integral validation | +| `canary.stickyKey.paramType`, `.paramName` | Source required when enabled at 1..99%; availability is a separate binding fact | +| `canary.canaryLabels`, `.stableLabels` | Both nonempty string maps; a shared key must have different values | +| `canary.fallbackPolicy` | STABLE, or REJECT | +| `sticky.enabled` | false; existing affinity activation requirements still apply | +| `sticky.cookieName` | Shenyu-Route base name, with the existing rule suffix; a custom name remains verbatim/shared | +| `sticky.maxAgeSeconds` | 3600 seconds | +| `sticky.secrets` | First HMAC key signs, all keys verify; configured values are sensitive | +| `sticky.onUnavailable` | REBIND; existing interpretation is unchanged | +| `sticky.key.type`, `.name` | Optional HEADER/COOKIE deterministic key; HEADER is the DTO default | + +For a present Canary object, the existing parser validates labels and conditional +requirements even when Canary is disabled. The contract reuses +`CanaryConfigValidator`; it does not create a second parser. Canary plus retries +to another target remains rejected until partition-aware failover exists. + +Sticky parsing follows the shared validator. It rejects string booleans and unknown key types. Affinity activation also depends on runtime configuration: +the existing runtime still needs usable secrets, cookie settings and lifetime. +Array element descriptions and conditional constraints are owned by semantic +validation, rather than silently enabling generic strict structural validation. + +## Validation, binding and updates + +Admin create/update/import/registration paths dispatch shared semantic validation +through the registry before writes. Admin's Canary dictionary checks remain +separate. The gateway validates a complete candidate before replacing the typed +handle and checks its actual ParameterData/PredicateJudge providers. A dictionary +entry can therefore be accepted by Admin and still be unavailable on a gateway. +Both failures use bounded field paths and codes; a missing binding is explicitly +`RUNTIME_BINDING_UNAVAILABLE`, with no raw provider exception/configuration value. + +| Boundary | Preserved version-one behavior | +| --- | --- | +| missing Java update value | no-op; previous typed handle remains | +| blank Admin value | accepted legacy input | +| blank gateway update | existing parse failure; previous typed handle remains | +| malformed/invalid candidate | rejected before replacing the previous handle | +| `{}` | parsed DTO defaults replace the previous handle | +| `removeRule` with null handle | current conditional removal leaves the typed handle present | +| `removeRule` with non-null handle | removes it; repeated removal is safe | +| disable | existing matching/lifecycle policy; this schema adds no universal cache clearing | + +The conditional removal limitation is intentionally characterized, not silently +strengthened by adopting a schema. Rewrite's blank-clear/invalid-expression +eviction policy is not applied to Divide. None of these per-handle checks +establishes atomic publication across selector, upstream or plugin caches. + +## Form projection and verification + +Metadata tests inventory every writable DTO property and verify the maintained +MySQL/PostgreSQL/Oracle/H2 field/control seeds. Their existing seven root controls +remain intact; the optional full catalog additionally describes nested JSON +fields. No IDs, seed rows or upgrade scripts change. In particular, existing +forms preset header/body limits to 10240/102400, while an omitted raw JSON field +has the runtime default 0. Both facts are explicitly described rather than +normalizing stored values or changing form behavior. + +The versioned `divide-rule-v1.tsv` corpus runs through common validation, real +Admin create/update/import services and the real gateway data handler. It checks +shared error paths/codes, missing/null/empty input, custom names, coercion, +Canary types/ranges/partitions/retry restrictions, sticky variants, binding +differences, valid-to-invalid retention and conditional removal. Existing routing, +Canary/failover, affinity, deterministic-key, retry, timeout and size-limit tests +are included in the focused verification; their behavior is not redesigned. + +```text +./mvnw -B -ntp -pl shenyu-admin,shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide -am verify -Dtest=RuleServiceTest,DivideRuleContractTest,CanaryConfigValidatorTest,*Divide*,*Canary*,*Sticky*,ConfigurationContractRegistryTest,RewriteRuleContractTest,PluginControllerTest -Dsurefire.failIfNoSpecifiedTests=false -Djacoco.skip=true -DskipRemoteResources=true -Dmaven.javadoc.skip=true +``` + +No full distribution/Docker E2E or released-version availability is implied by +the local deterministic checks. Pure validation runs on configuration updates; +no registry parsing or metadata projection is added to request forwarding. diff --git a/docs/rewrite-configuration-contract.md b/docs/rewrite-configuration-contract.md new file mode 100644 index 000000000000..a81f8c8d3230 --- /dev/null +++ b/docs/rewrite-configuration-contract.md @@ -0,0 +1,111 @@ + + +# Rewrite rule configuration, contract version 1 + +`RewriteRuleContract` publishes the existing rule-handle behavior through the +optional shared registry. Rewrite has no plugin- or selector-specific fields in +this contract. The shared catalog and Admin metadata endpoint describe these +four fields; `RewriteHandle` and the original JSON storage are unchanged. + +| Field | Declared type | Effective execution default | Meaning | +| --- | --- | --- | --- | +| `regex` | string | absent: no rewrite | Java regex, or existing brace-based placeholder expression | +| `replace` | string | absent: no rewrite | Replacement template | +| `percentage` | integer | omitted/null: 100 | Compared with an integer drawn from 0 through 99 | +| `rewriteMetaData` | boolean | omitted/null: false | Resolve metadata using the rewritten URI and effective context-path prefix | + +Version 1 preserves Gson coercion and unknown-field behavior. Field types describe +the DTO; this version does not enable generic strict structural validation. In +particular, it does not clamp or reject existing percentage values: 0 and negative +values never rewrite, 100 and values above 100 always pass the threshold. The +compatibility fixtures test these deterministic cases without statistical +sampling. A stricter range policy would require a separate version and migration. + +## Examples / 配置示例 + +An existing two-field handle still rewrites all matching requests by default: + +```json +{"regex":"/api/(.*)","replace":"/v2/$1"} +``` + +旧版双字段配置仍然有效;未填写 `percentage` 时默认按 100 处理, +未填写 `rewriteMetaData` 时默认不切换元数据。契约中的默认值仅用于描述执行行为, +不会自动写回已保存的 JSON。 + +The existing placeholder branch applies when both strings contain `{`: + +```json +{"regex":"/shenyu/{id}","replace":"/target/{id}","percentage":100,"rewriteMetaData":true} +``` + +当两个字符串都包含 `{` 时,仍使用现有占位符分支,不引入新的占位符语法。 +只填写一个表达式时允许保存,但不会执行改写。正则或替换模板确实不可用时, +仍由现有 `RewriteHandleUtils` 判断;运行时的原始 URI 回退保护保持不变。 + +## Update boundaries / 更新边界 + +| Input or operation | Admin acceptance | Gateway handle update | +| --- | --- | --- | +| missing Java value | accepted | leave previous cached handle unchanged | +| blank string | accepted | remove previous cached handle | +| `{}` | accepted | replace with a no-op handle | +| literal JSON `null` | rejected | evict previous cached handle | +| malformed JSON / incompatible object shape | rejected | existing parse exception; previous cached handle remains | +| unusable applicable regex/replacement | rejected | evict previous cached handle | +| incomplete expression | accepted | cache it; execution skips rewriting | +| rule removal | operation-specific | idempotent removal; handle is not required | + +“未传更新”“清空字符串”和“空对象”不是同一操作;无效表达式更新仍会淘汰旧改写, +不能套用 Divide 的“无效更新保留旧句柄”策略。契约返回校验事实,具体清除/淘汰行为 +仍由原数据处理器负责。 + +Admin create/update/import uses the generic registry, with no new rewrite-name +branch. Its existing direct validator remains a compatibility entry point. +Gateway publication uses the same applicability provider while preserving parse, +clear and eviction boundaries. No contract parsing runs on the request path. +Unknown configuration fields remain ignored, and existing matching, URI/context +handling, downstream continuation and metadata/RPC-type rules are unchanged. + +## Evidence + +The versioned `rewrite-rule-v1.tsv` corpus is packaged with the common contract. +Common validation, Admin direct validation and real create/update/import services, +and the gateway data handler plus real `RewritePlugin` execution consume it. +It covers existing two-field JSON, null defaults, legacy coercion/unknown fields, +0/100/out-of-range thresholds, blank/no-op/null/invalid updates, capture groups, +placeholder mode, repeated removal and metadata enabled/disabled/missing/context +prefix cases. Existing applicability, stale-handle and runtime fallback tests are +also retained. + +Metadata tests compare the four contract fields with DTO bean properties and the +maintained MySQL, PostgreSQL, Oracle and H2 form seed representations. No SQL seed +or field ID changes are needed: regex/replace use string controls, percentage a +numeric control, and rewriteMetaData a select control. Existing seeds explicitly +default rewriteMetaData to false; percentage's effective default comes from the +runtime, rather than being newly materialized in existing seed rows. + +```text +./mvnw -B -ntp -pl shenyu-admin,shenyu-plugin/shenyu-plugin-rewrite -am verify -Dtest=RewriteRuleContractTest,RewriteRuleHandleValidatorTest,RuleServiceTest,RewriteHandleUtilsTest,RewritePluginDataHandlerTest,RewritePluginTest,RewriteContractCompatibilityTest -Dsurefire.failIfNoSpecifiedTests=false -Djacoco.skip=true -DskipRemoteResources=true -Dmaven.javadoc.skip=true +``` + +This is source-build behavior for the current development branch, not a claim +that the contract has shipped in a released distribution. Full Docker E2E remains +separate from these local deterministic publication/runtime fixtures. diff --git a/shenyu-admin/src/main/java/org/apache/shenyu/admin/service/impl/RuleServiceImpl.java b/shenyu-admin/src/main/java/org/apache/shenyu/admin/service/impl/RuleServiceImpl.java index 4be21f251fe2..4fddb52f2d42 100644 --- a/shenyu-admin/src/main/java/org/apache/shenyu/admin/service/impl/RuleServiceImpl.java +++ b/shenyu-admin/src/main/java/org/apache/shenyu/admin/service/impl/RuleServiceImpl.java @@ -58,7 +58,10 @@ import org.apache.shenyu.admin.utils.Assert; import org.apache.shenyu.admin.utils.SessionUtil; import org.apache.shenyu.admin.validation.validator.AgentGatewayRuleHandleValidator; -import org.apache.shenyu.admin.validation.validator.RewriteRuleHandleValidator; +import org.apache.shenyu.common.config.contract.ConfigurationContractRegistry; +import org.apache.shenyu.common.config.contract.ConfigurationScope; +import org.apache.shenyu.common.config.contract.ConfigurationValidation; +import org.apache.shenyu.common.config.contract.ConfigurationValidationException; import org.apache.shenyu.common.constant.AdminConstants; import org.apache.shenyu.common.dto.ConditionData; import org.apache.shenyu.common.dto.RuleData; @@ -273,11 +276,16 @@ private void validateCanaryAndStickyConfig(final String selectorId, final String if (Objects.isNull(plugin) || !PluginEnum.DIVIDE.getName().equals(plugin.getName())) { return; } + validateRegisteredHandle(plugin.getName(), handle); try { DivideRuleHandle divide = CanaryConfigValidator.parseHandle(handle); - if (Objects.nonNull(divide.getCanary())) { - CanaryConfigValidator.validateExtensions(divide.getCanary(), - name -> validateCanaryDictionary("paramType", name), name -> validateCanaryDictionary("operator", name)); + if (Objects.nonNull(divide) && Objects.nonNull(divide.getCanary())) { + try { + CanaryConfigValidator.validateExtensions(divide.getCanary(), + name -> validateCanaryDictionary("paramType", name), name -> validateCanaryDictionary("operator", name)); + } catch (IllegalArgumentException error) { + throw ConfigurationValidationException.bindingUnavailable("divide", ConfigurationScope.RULE, "canary"); + } } StickySessionConfigValidator.validate(divide.getSticky()); } catch (IllegalArgumentException ex) { @@ -509,8 +517,14 @@ private void validateRuleHandle(final String selectorId, final String handle) { } if (PluginEnum.AGENT_GATEWAY.getName().equals(plugin.getName())) { AgentGatewayRuleHandleValidator.validate(handle); - } else if (PluginEnum.REWRITE.getName().equals(plugin.getName())) { - RewriteRuleHandleValidator.validate(handle); + } + validateRegisteredHandle(plugin.getName(), handle); + } + + private void validateRegisteredHandle(final String plugin, final String handle) { + ConfigurationValidation validation = ConfigurationContractRegistry.shared().validate(plugin, ConfigurationScope.RULE, "1", handle); + if (validation.status() == ConfigurationValidation.Status.INVALID) { + throw new ShenyuAdminException(new ConfigurationValidationException(validation).getMessage()); } } diff --git a/shenyu-admin/src/main/java/org/apache/shenyu/admin/validation/validator/RewriteRuleHandleValidator.java b/shenyu-admin/src/main/java/org/apache/shenyu/admin/validation/validator/RewriteRuleHandleValidator.java index 1ac4a189b0ba..7fba357cf8d0 100644 --- a/shenyu-admin/src/main/java/org/apache/shenyu/admin/validation/validator/RewriteRuleHandleValidator.java +++ b/shenyu-admin/src/main/java/org/apache/shenyu/admin/validation/validator/RewriteRuleHandleValidator.java @@ -17,14 +17,11 @@ package org.apache.shenyu.admin.validation.validator; -import com.google.gson.JsonSyntaxException; -import org.apache.commons.lang3.StringUtils; import org.apache.shenyu.admin.exception.ShenyuAdminException; -import org.apache.shenyu.common.dto.convert.rule.RewriteHandle; -import org.apache.shenyu.common.utils.GsonUtils; -import org.apache.shenyu.common.utils.RewriteHandleUtils; - -import java.util.Objects; +import org.apache.shenyu.common.config.contract.ConfigurationContractRegistry; +import org.apache.shenyu.common.config.contract.ConfigurationScope; +import org.apache.shenyu.common.config.contract.ConfigurationValidation; +import org.apache.shenyu.common.config.contract.ConfigurationViolation; /** * Validates rewrite rule handles before Admin stores them. @@ -41,22 +38,14 @@ private RewriteRuleHandleValidator() { * @param handle the rule handle supplied to Admin */ public static void validate(final String handle) { - if (StringUtils.isBlank(handle)) { - // an empty handle means the rule does not rewrite, which the plugin tolerates as well - return; - } - final RewriteHandle rewriteHandle; - try { - rewriteHandle = GsonUtils.getInstance().fromJson(handle, RewriteHandle.class); - } catch (JsonSyntaxException ex) { + ConfigurationValidation result = ConfigurationContractRegistry.shared().validate("rewrite", ConfigurationScope.RULE, "1", handle); + if (result.status() == ConfigurationValidation.Status.INVALID) { + ConfigurationViolation problem = result.violations().get(0); + if (problem.code() == ConfigurationViolation.Code.SEMANTIC_INVALID) { + throw new ShenyuAdminException("rewrite rule handle can not be applied, " + + ("regex".equals(problem.path()) ? "invalid regular expression" : "invalid replacement template")); + } throw new ShenyuAdminException("rewrite rule handle must be a valid JSON object"); } - if (Objects.isNull(rewriteHandle)) { - throw new ShenyuAdminException("rewrite rule handle must be a valid JSON object"); - } - final String problem = RewriteHandleUtils.applicabilityProblem(rewriteHandle.getRegex(), rewriteHandle.getReplace()); - if (Objects.nonNull(problem)) { - throw new ShenyuAdminException("rewrite rule handle can not be applied, " + problem); - } } } diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/RuleServiceTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/RuleServiceTest.java index 7987f86d6b73..e5e1032b8ac8 100644 --- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/RuleServiceTest.java +++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/service/RuleServiceTest.java @@ -59,6 +59,7 @@ import org.apache.shiro.authz.UnauthorizedException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -466,6 +467,83 @@ private void mockRewritePlugin() { .build()); } + @ParameterizedTest(name = "{0}") + @MethodSource("rewriteFixtures") + public void testRewriteFixtureAtWriteBoundaries(final String name, final boolean accepted, final String source, final String operation) { + mockRewritePlugin(); + exerciseRuleWriteFixture(accepted, source, operation); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("divideFixtures") + public void testDivideFixtureAtWriteBoundaries(final String name, final boolean accepted, final String source, final String operation, + final String path, final String code, final String dictionaryName) { + configureDivideSelector(); + if (!"-".equals(dictionaryName)) { + given(shenyuDictMapper.findByType("paramType")).willReturn(Collections.singletonList(dictionary(dictionaryName, true))); + } + ShenyuAdminException error = exerciseRuleWriteFixture(accepted, source, operation); + if (!accepted) { + assertTrue(error.getMessage().contains(path)); + assertTrue(error.getMessage().contains(code)); + } + } + + private ShenyuAdminException exerciseRuleWriteFixture(final boolean accepted, final String source, final String operation) { + RuleDTO candidate = buildRuleDTO("update".equals(operation) ? "123" : ""); + candidate.setHandle(source); + given(ruleMapper.selectById("123")).willReturn(buildRuleDO("123")); + given(ruleMapper.updateSelective(any())).willReturn(1); + given(ruleMapper.insertSelective(any())).willReturn(1); + given(ruleMapper.selectAll()).willReturn(Collections.emptyList()); + if (accepted) { + if ("import".equals(operation)) { + assertEquals(1, ruleService.importData(Collections.singletonList(candidate)).getSuccessCount()); + } else { + assertEquals(1, ruleService.createOrUpdate(candidate)); + } + return null; + } else { + ShenyuAdminException error; + if ("import".equals(operation)) { + error = assertThrows(ShenyuAdminException.class, () -> ruleService.importData(Collections.singletonList(candidate))); + } else { + error = assertThrows(ShenyuAdminException.class, () -> ruleService.createOrUpdate(candidate)); + } + verify(ruleMapper, never()).insertSelective(any()); + verify(ruleMapper, never()).updateSelective(any()); + verifyNoInteractions(ruleEventPublisher); + return error; + } + } + + private static java.util.stream.Stream divideFixtures() throws java.io.IOException { + try (var input = java.util.Objects.requireNonNull(RuleServiceTest.class.getResourceAsStream( + "/META-INF/shenyu/config-contract-fixtures/divide-rule-v1.tsv")); + var reader = new java.io.BufferedReader(new java.io.InputStreamReader(input, java.nio.charset.StandardCharsets.UTF_8))) { + return reader.lines().filter(line -> !line.isBlank() && !line.startsWith("#")).flatMap(line -> { + String[] fields = line.split("\\t", -1); + String source = "@missing".equals(fields[4]) ? null : "@blank".equals(fields[4]) ? "" : fields[4]; + return java.util.stream.Stream.of("create", "update", "import").map(operation -> + org.junit.jupiter.params.provider.Arguments.of(fields[0] + "-" + operation, Boolean.parseBoolean(fields[2]), source, + operation, fields[5], fields[6], fields[7])); + }).toList().stream(); + } + } + + private static java.util.stream.Stream rewriteFixtures() throws java.io.IOException { + try (var input = java.util.Objects.requireNonNull(RuleServiceTest.class.getResourceAsStream( + "/META-INF/shenyu/config-contract-fixtures/rewrite-rule-v1.tsv")); + var reader = new java.io.BufferedReader(new java.io.InputStreamReader(input, java.nio.charset.StandardCharsets.UTF_8))) { + return reader.lines().filter(line -> !line.isBlank() && !line.startsWith("#")).flatMap(line -> { + String[] fields = line.split("\\t", -1); + String source = "@missing".equals(fields[3]) ? null : "@blank".equals(fields[3]) ? "" : fields[3]; + return java.util.stream.Stream.of("create", "update", "import").map(operation -> + org.junit.jupiter.params.provider.Arguments.of(fields[0] + "-" + operation, Boolean.parseBoolean(fields[1]), source, operation)); + }).toList().stream(); + } + } + private void mockAgentGatewayPlugin() { given(selectorMapper.selectById("456")).willReturn(buildSelectorDO()); given(pluginMapper.selectById("789")).willReturn(PluginDO.builder() @@ -864,11 +942,11 @@ public void testInvalidStickyNeverWritesOrPublishes(final String stickyPatch) { @Test public void testStickyErrorsNameTheField() { - assertStickyError("{\"enabled\":true,\"secrets\":\"s\"}", "sticky.secrets must be an array"); + assertStickyError("{\"enabled\":true,\"secrets\":\"s\"}", "Invalid configuration: divide RULE sticky.secrets INVALID_TYPE"); assertStickyError("{\"enabled\":true,\"secrets\":[\"secret\"],\"cookieName\":null}", "sticky.cookieName must not be blank; omit it to use the default"); assertStickyError("{\"enabled\":true,\"secrets\":[\"secret\"],\"key\":{\"name\":\"X\",\"type\":\"cookie\"}}", - "sticky.key.type must be HEADER or COOKIE, got: cookie"); + "Invalid configuration: divide RULE sticky.key.type SEMANTIC_INVALID"); } private void assertStickyError(final String stickyPatch, final String message) { diff --git a/shenyu-admin/src/test/java/org/apache/shenyu/admin/validation/validator/RewriteRuleHandleValidatorTest.java b/shenyu-admin/src/test/java/org/apache/shenyu/admin/validation/validator/RewriteRuleHandleValidatorTest.java index 95c93957f056..b3121dadca11 100644 --- a/shenyu-admin/src/test/java/org/apache/shenyu/admin/validation/validator/RewriteRuleHandleValidatorTest.java +++ b/shenyu-admin/src/test/java/org/apache/shenyu/admin/validation/validator/RewriteRuleHandleValidatorTest.java @@ -21,6 +21,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import org.junit.jupiter.params.provider.MethodSource; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -31,6 +32,28 @@ */ public final class RewriteRuleHandleValidatorTest { + @ParameterizedTest(name = "{0}") + @MethodSource("fixtures") + public void testSharedFixtures(final String name, final boolean accepted, final String source) { + if (accepted) { + assertDoesNotThrow(() -> RewriteRuleHandleValidator.validate(source)); + } else { + assertThrows(ShenyuAdminException.class, () -> RewriteRuleHandleValidator.validate(source)); + } + } + + private static java.util.stream.Stream fixtures() throws java.io.IOException { + try (var input = java.util.Objects.requireNonNull(RewriteRuleHandleValidatorTest.class.getResourceAsStream( + "/META-INF/shenyu/config-contract-fixtures/rewrite-rule-v1.tsv")); + var reader = new java.io.BufferedReader(new java.io.InputStreamReader(input, java.nio.charset.StandardCharsets.UTF_8))) { + return reader.lines().filter(line -> !line.isBlank() && !line.startsWith("#")).map(line -> { + String[] fields = line.split("\\t", -1); + String source = "@missing".equals(fields[3]) ? null : "@blank".equals(fields[3]) ? "" : fields[3]; + return org.junit.jupiter.params.provider.Arguments.of(fields[0], Boolean.parseBoolean(fields[1]), source); + }).toList().stream(); + } + } + @Test public void testApplicableHandles() { assertDoesNotThrow(() -> RewriteRuleHandleValidator.validate(null)); diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/ConfigurationContract.java b/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/ConfigurationContract.java index 22bab0df7332..b7d95aed4a3c 100644 --- a/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/ConfigurationContract.java +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/ConfigurationContract.java @@ -70,15 +70,22 @@ public enum Type { * @param sensitive whether tooling must omit supplied values * @param minimum optional inclusive numeric lower bound * @param maximum optional inclusive numeric upper bound - * @param values optional closed string enumeration; null means unrestricted (never inferred for SPI names) + * @param values optional closed string enumeration (never inferred for SPI names) + * @param description field meaning and compatibility notes */ public record Field(Type type, boolean required, boolean nullable, String effectiveDefault, String unit, - boolean sensitive, Long minimum, Long maximum, List values) { + boolean sensitive, Long minimum, Long maximum, List values, String description) { + + public Field(final Type type, final boolean required, final boolean nullable, final String effectiveDefault, final String unit, + final boolean sensitive, final Long minimum, final Long maximum, final List values) { + this(type, required, nullable, effectiveDefault, unit, sensitive, minimum, maximum, values, ""); + } public Field { Objects.requireNonNull(type); unit = Objects.requireNonNullElse(unit, ""); values = Objects.isNull(values) ? List.of() : List.copyOf(values); + description = Objects.requireNonNullElse(description, ""); if (values.size() > 64 || Objects.nonNull(minimum) && Objects.nonNull(maximum) && minimum > maximum) { throw new IllegalArgumentException("Invalid configuration field constraints"); } diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/ConfigurationValidationException.java b/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/ConfigurationValidationException.java new file mode 100644 index 000000000000..5e88cea10619 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/ConfigurationValidationException.java @@ -0,0 +1,54 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.shenyu.common.config.contract; + +import java.util.List; + +/** Bounded shared validation or runtime-binding failure without input values or parser causes. */ +public final class ConfigurationValidationException extends IllegalArgumentException { + + private static final long serialVersionUID = 1L; + + private final ConfigurationValidation validation; + + public ConfigurationValidationException(final ConfigurationValidation validation) { + super("Invalid configuration: " + validation.plugin() + " " + validation.scope() + " " + + validation.violations().get(0).path() + " " + validation.violations().get(0).code()); + this.validation = validation; + } + + /** + * Get the shared, secret-free failure facts. + * @return bounded diagnostic result + */ + public ConfigurationValidation validation() { + return validation; + } + + /** + * Classify an environment-specific extension binding failure separately from configuration semantics. + * @param plugin trusted plugin identity + * @param scope scope + * @param path declared field path + * @return bounded binding failure with no raw provider exception + */ + public static ConfigurationValidationException bindingUnavailable(final String plugin, final ConfigurationScope scope, final String path) { + return new ConfigurationValidationException(new ConfigurationValidation(plugin, scope, "1", ConfigurationValidation.Status.INVALID, + List.of(new ConfigurationViolation(path, ConfigurationViolation.Code.RUNTIME_BINDING_UNAVAILABLE)))); + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/DivideRuleContract.java b/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/DivideRuleContract.java new file mode 100644 index 000000000000..75b4b994c4c4 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/DivideRuleContract.java @@ -0,0 +1,127 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.shenyu.common.config.contract; + +import org.apache.commons.lang3.StringUtils; +import org.apache.shenyu.common.dto.convert.rule.canary.CanaryConfigValidator; + +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import static org.apache.shenyu.common.config.contract.ConfigurationContract.Type.ARRAY; +import static org.apache.shenyu.common.config.contract.ConfigurationContract.Type.BOOLEAN; +import static org.apache.shenyu.common.config.contract.ConfigurationContract.Type.INTEGER; +import static org.apache.shenyu.common.config.contract.ConfigurationContract.Type.OBJECT; +import static org.apache.shenyu.common.config.contract.ConfigurationContract.Type.STRING; + +/** Version-one inventory and existing pure semantic validation for Divide rule handles. */ +public final class DivideRuleContract implements ConfigurationContractProvider { + + private static final ConfigurationContract CONTRACT = new ConfigurationContract("divide", ConfigurationScope.RULE, "1", false, + ConfigurationContract.UnknownFields.ALLOW, fields(), + Map.of("missingUpdate", "retain", "blankAdmin", "accepted legacy input", "blankGatewayUpdate", "parse failure; retain", + "invalidUpdate", "reject; retain", "remove", "only non-null input handles remove the cached handle", + "disable", "matching/lifecycle owned; no universal cache clearing", "defaults", "descriptive only; never persisted")); + + @Override + public ConfigurationContract contract() { + return CONTRACT; + } + + @Override + public List validateSemantic(final String source) { + // Admin historically permits blank handles; the gateway's parser still rejects blank updates. + if (StringUtils.isBlank(source)) { + return List.of(); + } + try { + CanaryConfigValidator.parseHandle(source); + return List.of(); + } catch (IllegalArgumentException error) { + String message = Objects.toString(error.getMessage(), ""); + String normalized = message.replaceAll("\\[[0-9]+\\]", "[]"); + String path = CONTRACT.fields().keySet().stream().filter(normalized::startsWith) + .max(Comparator.comparingInt(String::length)).orElse(message.startsWith("Canary ") ? "canary" : "$"); + ConfigurationViolation.Code code = ConfigurationViolation.Code.SEMANTIC_INVALID; + if (message.startsWith("Invalid Divide handle JSON")) { + code = ConfigurationViolation.Code.INVALID_JSON; + } else if (message.contains("must be an integer") || message.contains("must be a boolean") + || message.contains("must be an object") || message.contains("must be an array") || message.contains("must be a string")) { + code = ConfigurationViolation.Code.INVALID_TYPE; + } else if (message.contains("must be between")) { + code = ConfigurationViolation.Code.OUT_OF_RANGE; + } + return List.of(new ConfigurationViolation(path, code)); + } + } + + private static Map fields() { + Map fields = new LinkedHashMap<>(); + add(fields, "loadBalance", STRING, "random", "", false, "SPI name; custom providers are not a closed built-in enum"); + add(fields, "retryStrategy", STRING, "current", "", false, "Legacy retry strategy name; current/failover interpretation is unchanged"); + add(fields, "retryBackOffSpec", STRING, "default", "", false, "default/fixed/exponential; unknown names retain legacy fallback"); + add(fields, "retry", INTEGER, "3", "attempt retries", false, "Existing retry count; no new root-field range policy"); + add(fields, "timeout", INTEGER, "3000", "milliseconds", false, "Upstream timeout; inherited runtime interpretation is unchanged"); + add(fields, "requestTimeout", INTEGER, null, "milliseconds", false, "Overall HTTPRoute request budget; absent uses legacy timeout handling and zero disables the deadline"); + add(fields, "headerMaxSize", INTEGER, "0", "bytes", false, "UTF-8 plus framing allowance; non-positive disables checking; legacy form preset is 10240"); + add(fields, "requestMaxSize", INTEGER, "0", "bytes", false, "Non-positive disables checking; legacy form preset is 102400"); + add(fields, "poolGroup", STRING, null, "", false, "Optional named upstream connection pool; absent or empty uses the shared default pool"); + add(fields, "canary", OBJECT, null, "", false, "Absent/null uses legacy routing; a present object must satisfy the existing partition validator"); + add(fields, "canary.enabled", BOOLEAN, "false", "", false, "False selects Stable; present values must be JSON booleans"); + add(fields, "canary.conditions", ARRAY, null, "", true, "Optional request predicates; explicit null is invalid; an empty list admits all requests"); + add(fields, "canary.conditions[].paramType", STRING, null, "", false, "ParameterData SPI name; dictionary and installed-provider checks are separate"); + add(fields, "canary.conditions[].operator", STRING, null, "", false, "PredicateJudge SPI name, including custom extensions"); + add(fields, "canary.conditions[].paramName", STRING, null, "", true, "Required for named header/cookie/query/post sources"); + add(fields, "canary.conditions[].paramValue", STRING, null, "", true, "Required except isBlank; existing regex/time semantics apply"); + add(fields, "canary.matchMode", INTEGER, "0", "", false, "0 AND or 1 OR; explicit null and other values are invalid"); + add(fields, "canary.percentage", INTEGER, "0", "percent", false, "Existing closed range 0..100; no fractional or string coercion"); + add(fields, "canary.stickyKey", OBJECT, null, "", true, "Required when enabled with percentage 1..99; explicit null is invalid"); + add(fields, "canary.stickyKey.paramType", STRING, null, "", false, "ParameterData SPI name; availability is a binding fact"); + add(fields, "canary.stickyKey.paramName", STRING, null, "", true, "Source-specific name; required for named built-in sources"); + add(fields, "canary.canaryLabels", OBJECT, null, "", true, "Required nonempty string labels for a present Canary object"); + add(fields, "canary.stableLabels", OBJECT, null, "", true, "Required labels; partitions must share a key with different values"); + add(fields, "canary.fallbackPolicy", STRING, "STABLE", "", false, "STABLE or REJECT for an initially empty Canary pool"); + add(fields, "sticky", OBJECT, null, "", true, "Optional HTTP affinity; parser acceptance is not proof that affinity can activate"); + add(fields, "sticky.enabled", BOOLEAN, "false", "", false, "Activation also requires usable secrets, cookie name and positive lifetime"); + add(fields, "sticky.cookieName", STRING, "Shenyu-Route", "", false, "Default base name receives a rule suffix; custom names remain shared verbatim"); + add(fields, "sticky.maxAgeSeconds", INTEGER, "3600", "seconds", false, "Binding lifetime; existing affinity activation handles unusable values"); + add(fields, "sticky.secrets", ARRAY, null, "", true, "First HMAC key signs; all keys verify; never expose configured values"); + add(fields, "sticky.onUnavailable", STRING, "REBIND", "", false, "Existing unavailable-target policy; no new parser rejection"); + add(fields, "sticky.key", OBJECT, null, "", true, "Optional deterministic key; effective only while enclosing affinity is active"); + add(fields, "sticky.key.type", STRING, "HEADER", "", false, "Current DTO enum HEADER/COOKIE; existing unknown/null handling is retained"); + add(fields, "sticky.key.name", STRING, null, "", true, "Header or cookie name; request values never belong in metadata"); + return fields; + } + + private static void add(final Map fields, final String path, final ConfigurationContract.Type type, + final String defaultValue, final String unit, final boolean sensitive, final String description) { + Long minimum = "canary.percentage".equals(path) || "canary.matchMode".equals(path) ? 0L : null; + Long maximum = null; + if ("canary.percentage".equals(path)) { + maximum = 100L; + } else if ("canary.matchMode".equals(path)) { + maximum = 1L; + } + List values = "canary.fallbackPolicy".equals(path) ? List.of("STABLE", "REJECT") : List.of(); + fields.put(path, new ConfigurationContract.Field(type, false, !path.startsWith("canary."), defaultValue, unit, sensitive, + minimum, maximum, values, description)); + } +} diff --git a/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/RewriteRuleContract.java b/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/RewriteRuleContract.java new file mode 100644 index 000000000000..7b2d2fd3fbc3 --- /dev/null +++ b/shenyu-common/src/main/java/org/apache/shenyu/common/config/contract/RewriteRuleContract.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.shenyu.common.config.contract; + +import com.google.gson.JsonSyntaxException; +import org.apache.commons.lang3.StringUtils; +import org.apache.shenyu.common.dto.convert.rule.RewriteHandle; +import org.apache.shenyu.common.utils.GsonUtils; +import org.apache.shenyu.common.utils.RewriteHandleUtils; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** Version-one metadata and existing applicability rules for rewrite rule handles. */ +public final class RewriteRuleContract implements ConfigurationContractProvider { + + private static final ConfigurationContract CONTRACT = new ConfigurationContract("rewrite", ConfigurationScope.RULE, "1", false, + ConfigurationContract.UnknownFields.ALLOW, + Map.of("regex", field(ConfigurationContract.Type.STRING, null, "", true, "Java regex, or the existing brace-based placeholder expression"), + "replace", field(ConfigurationContract.Type.STRING, null, "", true, "Replacement template; incomplete expressions are no-ops"), + "percentage", field(ConfigurationContract.Type.INTEGER, "100", "percent", false, "Legacy threshold; values are neither clamped nor range-rejected"), + "rewriteMetaData", field(ConfigurationContract.Type.BOOLEAN, "false", "", false, "Look up metadata for the rewritten URI when true")), + Map.of("missingUpdate", "retain", "blankUpdate", "clear", "emptyObjectUpdate", "replace with no-op", + "explicitNullUpdate", "evict", "malformedJsonUpdate", "throw; retain", + "invalidApplicableExpressionUpdate", "evict", "remove", "idempotent; handle not required")); + + @Override + public ConfigurationContract contract() { + return CONTRACT; + } + + @Override + public List validateSemantic(final String source) { + if (StringUtils.isBlank(source)) { + return List.of(); + } + final RewriteHandle handle; + try { + handle = GsonUtils.getInstance().fromJson(source, RewriteHandle.class); + } catch (JsonSyntaxException error) { + return List.of(new ConfigurationViolation("$", ConfigurationViolation.Code.INVALID_JSON)); + } + if (Objects.isNull(handle)) { + return List.of(new ConfigurationViolation("$", ConfigurationViolation.Code.INVALID_JSON)); + } + String problem = RewriteHandleUtils.applicabilityProblem(handle.getRegex(), handle.getReplace()); + if (Objects.isNull(problem)) { + return List.of(); + } + String path = problem.startsWith("invalid regular expression:") ? "regex" : "replace"; + return List.of(new ConfigurationViolation(path, ConfigurationViolation.Code.SEMANTIC_INVALID)); + } + + private static ConfigurationContract.Field field(final ConfigurationContract.Type type, final String defaultValue, + final String unit, final boolean sensitive, final String description) { + return new ConfigurationContract.Field(type, false, true, defaultValue, unit, sensitive, null, null, List.of(), description); + } +} diff --git a/shenyu-common/src/main/resources/META-INF/services/org.apache.shenyu.common.config.contract.ConfigurationContractProvider b/shenyu-common/src/main/resources/META-INF/services/org.apache.shenyu.common.config.contract.ConfigurationContractProvider index 513d9b86388b..b4d381f988af 100644 --- a/shenyu-common/src/main/resources/META-INF/services/org.apache.shenyu.common.config.contract.ConfigurationContractProvider +++ b/shenyu-common/src/main/resources/META-INF/services/org.apache.shenyu.common.config.contract.ConfigurationContractProvider @@ -14,3 +14,5 @@ # limitations under the License. org.apache.shenyu.common.config.contract.AgentGatewayPluginContract +org.apache.shenyu.common.config.contract.RewriteRuleContract +org.apache.shenyu.common.config.contract.DivideRuleContract diff --git a/shenyu-common/src/main/resources/META-INF/shenyu/config-contract-fixtures/divide-rule-v1.tsv b/shenyu-common/src/main/resources/META-INF/shenyu/config-contract-fixtures/divide-rule-v1.tsv new file mode 100644 index 000000000000..d6f94f702a0f --- /dev/null +++ b/shenyu-common/src/main/resources/META-INF/shenyu/config-contract-fixtures/divide-rule-v1.tsv @@ -0,0 +1,48 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# +# id\tsharedStatus\tadminAccepted\tgatewayAction\tsource\tpath\tcode\tdictionaryName +missing VALID true RETAIN @missing - - - +blank VALID true THROW_RETAIN @blank - - - +empty VALID true REPLACE {} - - - +literal-null INVALID false REJECT_RETAIN null $ INVALID_TYPE - +malformed INVALID false REJECT_RETAIN { $ INVALID_JSON - +array-root INVALID false REJECT_RETAIN [] $ INVALID_TYPE - +bad-root-field INVALID false REJECT_RETAIN {"retry":{}} $ INVALID_JSON - +custom-names VALID true REPLACE {"loadBalance":"contract-custom","retryStrategy":"custom","retryBackOffSpec":"custom"} - - - +named-pool-group VALID true REPLACE {"poolGroup":"bulk"} - - - +request-budget VALID true REPLACE {"requestTimeout":1200} - - - +coercion VALID true REPLACE {"retry":"2","timeout":"9000","requestMaxSize":"1024"} - - - +nullable VALID true REPLACE {"retry":null,"timeout":null,"requestTimeout":null,"poolGroup":null,"canary":null,"sticky":null} - - - +legacy-ranges VALID true REPLACE {"retry":-1,"timeout":-1,"headerMaxSize":-1,"requestMaxSize":-1} - - - +disabled-canary VALID true REPLACE {"canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"},"enabled":false}} - - - +full-canary VALID true REPLACE {"canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"},"enabled":true,"percentage":100}} - - - +empty-canary INVALID false REJECT_RETAIN {"canary":{}} canary.stableLabels INVALID_TYPE - +canary-range INVALID false REJECT_RETAIN {"canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"},"percentage":101}} canary.percentage OUT_OF_RANGE - +canary-fraction INVALID false REJECT_RETAIN {"canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"},"percentage":20.5}} canary.percentage INVALID_TYPE - +canary-string INVALID false REJECT_RETAIN {"canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"},"percentage":"20"}} canary.percentage INVALID_TYPE - +canary-null INVALID false REJECT_RETAIN {"canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"},"percentage":null}} canary.percentage INVALID_TYPE - +canary-boolean INVALID false REJECT_RETAIN {"canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"},"enabled":"false"}} canary.enabled INVALID_TYPE - +canary-failover INVALID false REJECT_RETAIN {"retry":1,"retryStrategy":"failover","canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"}}} canary SEMANTIC_INVALID - +canary-missing-key INVALID false REJECT_RETAIN {"canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"},"enabled":true,"percentage":20}} canary.stickyKey SEMANTIC_INVALID - +canary-valid-key VALID true REPLACE {"canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"},"enabled":true,"percentage":20,"stickyKey":{"paramType":"header","paramName":"x-user"}}} - - header +canary-labels INVALID false REJECT_RETAIN {"canary":{"stableLabels":{"release":1},"canaryLabels":{"release":"canary"}}} canary.stableLabels INVALID_TYPE - +canary-conditions-null INVALID false REJECT_RETAIN {"canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"},"conditions":null}} canary.conditions INVALID_TYPE - +canary-fallback INVALID false REJECT_RETAIN {"canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"},"fallbackPolicy":"INVALID"}} canary.fallbackPolicy SEMANTIC_INVALID - +sticky-defaults VALID true REPLACE {"sticky":{}} - - - +sticky-enabled-string INVALID false REJECT_RETAIN {"sticky":{"enabled":"true","maxAgeSeconds":"3600","key":{"type":"HEADER","name":"x-user"},"secrets":["fixture-key"]}} sticky.enabled INVALID_TYPE - +sticky-unknown-key-type INVALID false REJECT_RETAIN {"sticky":{"enabled":true,"maxAgeSeconds":-1,"secrets":[],"key":{"type":"UNKNOWN"}}} sticky.key.type SEMANTIC_INVALID - +sticky-wrong-shape INVALID false REJECT_RETAIN {"sticky":[]} sticky INVALID_TYPE - +binding-differs VALID true BINDING_RETAIN {"canary":{"stableLabels":{"release":"stable"},"canaryLabels":{"release":"canary"},"stickyKey":{"paramType":"contract-missing"}}} canary RUNTIME_BINDING_UNAVAILABLE contract-missing diff --git a/shenyu-common/src/main/resources/META-INF/shenyu/config-contract-fixtures/rewrite-rule-v1.tsv b/shenyu-common/src/main/resources/META-INF/shenyu/config-contract-fixtures/rewrite-rule-v1.tsv new file mode 100644 index 000000000000..9484808fab40 --- /dev/null +++ b/shenyu-common/src/main/resources/META-INF/shenyu/config-contract-fixtures/rewrite-rule-v1.tsv @@ -0,0 +1,38 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# +# id\tadminAccepted\tupdateAction\tsource\trequestPath\trewrittenAttribute\tmetadata\tcontextPath +missing true RETAIN @missing /old /new none @missing +blank true CLEAR @blank /old @none none @missing +empty-object true REPLACE {} /old @none none @missing +literal-null false EVICT null /old @none none @missing +malformed false THROW_RETAIN { /old /new none @missing +two-field true REPLACE {"regex":"test","replace":"rewrite"} /shenyu/test /shenyu/rewrite none @missing +nullable-defaults true REPLACE {"regex":"/old","replace":"/new","percentage":null,"rewriteMetaData":null} /old /new none @missing +zero true REPLACE {"regex":"/old","replace":"/new","percentage":0} /old @none none @missing +hundred true REPLACE {"regex":"/old","replace":"/new","percentage":100} /old /new none @missing +negative true REPLACE {"regex":"/old","replace":"/new","percentage":-1} /old @none none @missing +over-hundred true REPLACE {"regex":"/old","replace":"/new","percentage":101} /old /new none @missing +coercion-and-unknown true REPLACE {"regex":"/old","replace":"/new","percentage":"100","extra":"ignored"} /old /new none @missing +incomplete true REPLACE {"regex":"[a"} /old @none none @missing +capture true REPLACE {"regex":"/(old)","replace":"/new/$1"} /old /new/old none @missing +placeholder true REPLACE {"regex":"/shenyu/{id}","replace":"/target/{id}"} /shenyu/42 /target/42 none @missing +invalid-regex false EVICT {"regex":"[a","replace":"/new"} /old @none none @missing +invalid-replacement false EVICT {"regex":"test","replace":"/new/$1"} /old @none none @missing +invalid-secret-group false EVICT {"regex":"test","replace":"/${SECRET}"} /old @none none @missing +metadata-enabled true REPLACE {"regex":"/old","replace":"/new","rewriteMetaData":true} /old /new enabled @missing +metadata-disabled true REPLACE {"regex":"/old","replace":"/new","rewriteMetaData":true} /old /new disabled @missing +metadata-missing true REPLACE {"regex":"/old","replace":"/new","rewriteMetaData":true} /old /new missing @missing +metadata-context true REPLACE {"regex":"/ctx/old","replace":"/new","rewriteMetaData":true} /ctx/old /new enabled /ctx diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/config/contract/DivideRuleContractTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/config/contract/DivideRuleContractTest.java new file mode 100644 index 000000000000..51eac393749b --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/config/contract/DivideRuleContractTest.java @@ -0,0 +1,125 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.shenyu.common.config.contract; + +import org.apache.shenyu.common.dto.ConditionData; +import org.apache.shenyu.common.dto.convert.rule.canary.CanaryConfig; +import org.apache.shenyu.common.dto.convert.rule.canary.StickyKeyConfig; +import org.apache.shenyu.common.dto.convert.rule.impl.DivideRuleHandle; +import org.apache.shenyu.common.dto.convert.rule.sticky.DeterministicKeyConfig; +import org.apache.shenyu.common.dto.convert.rule.sticky.StickySessionConfig; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.beans.Introspector; +import java.util.Arrays; +import java.util.Set; +import java.util.Map; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class DivideRuleContractTest { + + @ParameterizedTest(name = "{0}") + @MethodSource("fixtures") + void canonicalValidationFactsAreShared(final String name, final String expected, final String source, final String path, final String code) { + ConfigurationValidation result = ConfigurationContractRegistry.shared().validate("divide", ConfigurationScope.RULE, "1", source); + assertEquals(expected, result.status().name()); + if ("INVALID".equals(expected)) { + assertEquals(path, result.violations().get(0).path()); + assertEquals(code, result.violations().get(0).code().name()); + } + } + + @Test + void inventoryIncludesEveryCurrentDtoFieldAndNestedField() throws Exception { + ConfigurationContract contract = new DivideRuleContract().contract(); + assertFields(contract, "", DivideRuleHandle.class); + assertFields(contract, "canary.", CanaryConfig.class); + assertFields(contract, "canary.stickyKey.", StickyKeyConfig.class); + assertFields(contract, "canary.conditions[].", ConditionData.class); + assertFields(contract, "sticky.", StickySessionConfig.class); + assertFields(contract, "sticky.key.", DeterministicKeyConfig.class); + DivideRuleHandle defaults = DivideRuleHandle.newInstance(); + assertEquals(defaults.getLoadBalance(), contract.fields().get("loadBalance").effectiveDefault()); + assertEquals(String.valueOf(defaults.getTimeout()), contract.fields().get("timeout").effectiveDefault()); + assertEquals(String.valueOf(defaults.getRetry()), contract.fields().get("retry").effectiveDefault()); + assertEquals("milliseconds", contract.fields().get("timeout").unit()); + assertEquals("3600", contract.fields().get("sticky.maxAgeSeconds").effectiveDefault()); + assertEquals("0", contract.fields().get("canary.percentage").effectiveDefault()); + assertTrue(contract.fields().get("sticky.secrets").sensitive()); + assertTrue(contract.fields().get("loadBalance").values().isEmpty(), "SPI names are open-ended"); + } + + private void assertFields(final ConfigurationContract contract, final String prefix, final Class type) throws Exception { + Set expected = Arrays.stream(Introspector.getBeanInfo(type, Object.class).getPropertyDescriptors()) + .filter(property -> java.util.Objects.nonNull(property.getWriteMethod())) + .map(property -> prefix + property.getName()).collect(Collectors.toSet()); + for (String path : expected) { + assertTrue(contract.fields().containsKey(path), path); + assertTrue(!contract.fields().get(path).description().isBlank(), path); + } + Set actual = contract.fields().keySet().stream().filter(path -> path.startsWith(prefix)) + .filter(path -> !path.substring(prefix.length()).contains(".")).collect(Collectors.toSet()); + assertEquals(expected, actual); + } + + @Test + void existingFormProjectionKeepsControlTypesAndConfiguredPresets() throws Exception { + Path root = Path.of("").toAbsolutePath(); + while (java.util.Objects.nonNull(root) && !Files.isDirectory(root.resolve("db/init"))) { + root = root.getParent(); + } + assertNotNull(root); + final Map controls = Map.of("loadBalance", "loadStrategy',3", "retry", "retryCount',1", "timeout", "timeout',1", + "headerMaxSize", "headerMaxSize',1", "requestMaxSize", "requestMaxSize',1", "retryStrategy", "retryStrategy',3", + "retryBackOffSpec", "retryBackOffSpec',3"); + for (String seed : new String[]{"db/init/mysql/schema.sql", "db/init/oracle/schema.sql", "db/init/pg/create-table.sql", + "shenyu-admin/src/main/resources/sql-script/h2/schema.sql"}) { + String sql = Files.readString(root.resolve(seed)); + for (Map.Entry field : controls.entrySet()) { + assertTrue(Arrays.stream(sql.split(";")).anyMatch(statement -> statement.toLowerCase(java.util.Locale.ROOT).contains("plugin_handle") + && statement.replaceAll("\\s+", "").contains("'5','" + field.getKey() + "','" + field.getValue() + ",2,")), + seed + " missing field/control " + field.getKey()); + } + } + ConfigurationContract contract = new DivideRuleContract().contract(); + assertTrue(contract.fields().get("headerMaxSize").description().contains("10240")); + assertTrue(contract.fields().get("requestMaxSize").description().contains("102400")); + assertEquals("0", contract.fields().get("headerMaxSize").effectiveDefault()); + assertEquals("0", contract.fields().get("requestMaxSize").effectiveDefault()); + } + + private static java.util.stream.Stream fixtures() throws java.io.IOException { + try (var input = java.util.Objects.requireNonNull(DivideRuleContractTest.class.getResourceAsStream( + "/META-INF/shenyu/config-contract-fixtures/divide-rule-v1.tsv")); + var reader = new java.io.BufferedReader(new java.io.InputStreamReader(input, java.nio.charset.StandardCharsets.UTF_8))) { + return reader.lines().filter(line -> !line.isBlank() && !line.startsWith("#")).map(line -> { + String[] fields = line.split("\\t", -1); + String source = "@missing".equals(fields[4]) ? null : "@blank".equals(fields[4]) ? "" : fields[4]; + return org.junit.jupiter.params.provider.Arguments.of(fields[0], fields[1], source, fields[5], fields[6]); + }).toList().stream(); + } + } +} diff --git a/shenyu-common/src/test/java/org/apache/shenyu/common/config/contract/RewriteRuleContractTest.java b/shenyu-common/src/test/java/org/apache/shenyu/common/config/contract/RewriteRuleContractTest.java new file mode 100644 index 000000000000..9e2d6531c39a --- /dev/null +++ b/shenyu-common/src/test/java/org/apache/shenyu/common/config/contract/RewriteRuleContractTest.java @@ -0,0 +1,88 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.shenyu.common.config.contract; + +import org.apache.shenyu.common.dto.convert.rule.RewriteHandle; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.beans.Introspector; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Set; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +class RewriteRuleContractTest { + + @ParameterizedTest(name = "{0}") + @MethodSource("fixtures") + void sharedValidatorPreservesLegacyAcceptance(final String name, final boolean accepted, final String source) { + ConfigurationValidation result = ConfigurationContractRegistry.shared().validate("rewrite", ConfigurationScope.RULE, "1", source); + assertEquals(accepted, result.status() == ConfigurationValidation.Status.VALID); + assertFalse(result.toString().contains("SECRET")); + } + + @Test + void metadataMatchesDtoAndMaintainedFormSeeds() throws Exception { + ConfigurationContract contract = new RewriteRuleContract().contract(); + Set properties = Arrays.stream(Introspector.getBeanInfo(RewriteHandle.class, Object.class).getPropertyDescriptors()) + .map(property -> property.getName()).collect(Collectors.toSet()); + assertEquals(properties, contract.fields().keySet()); + assertEquals("100", contract.fields().get("percentage").effectiveDefault()); + assertEquals("false", contract.fields().get("rewriteMetaData").effectiveDefault()); + assertFalse(contract.structuralValidation()); + assertEquals(ConfigurationContract.UnknownFields.ALLOW, contract.unknownFields()); + assertEquals("retain", contract.operations().get("missingUpdate")); + Path root = Path.of("").toAbsolutePath(); + while (java.util.Objects.nonNull(root) && !Files.isDirectory(root.resolve("db/init"))) { + root = root.getParent(); + } + assertNotNull(root, "Repository form seeds must be available for this metadata check"); + final Map controls = Map.of("regex", 2, "replace", 2, "percentage", 1, "rewriteMetaData", 3); + for (String seed : new String[]{"db/init/mysql/schema.sql", "db/init/oracle/schema.sql", "db/init/pg/create-table.sql", + "shenyu-admin/src/main/resources/sql-script/h2/schema.sql"}) { + String sql = Files.readString(root.resolve(seed)); + for (String field : properties) { + assertTrue(Arrays.stream(sql.split(";")).anyMatch(line -> line.toLowerCase(java.util.Locale.ROOT).contains("plugin_handle") + && line.replaceAll("\\s+", "").contains("'3','" + field + "','" + field + "'," + controls.get(field) + ",")), + seed + " missing field/control " + field); + assertFalse(contract.fields().get(field).description().isBlank()); + } + } + } + + private static java.util.stream.Stream fixtures() throws java.io.IOException { + try (var input = java.util.Objects.requireNonNull(RewriteRuleContractTest.class.getResourceAsStream( + "/META-INF/shenyu/config-contract-fixtures/rewrite-rule-v1.tsv")); + var reader = new java.io.BufferedReader(new java.io.InputStreamReader(input, java.nio.charset.StandardCharsets.UTF_8))) { + return reader.lines().filter(line -> !line.isBlank() && !line.startsWith("#")).map(line -> { + String[] fields = line.split("\\t", -1); + String source = "@missing".equals(fields[3]) ? null : "@blank".equals(fields[3]) ? "" : fields[3]; + return org.junit.jupiter.params.provider.Arguments.of(fields[0], Boolean.parseBoolean(fields[1]), source); + }).toList().stream(); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/main/java/org/apache/shenyu/plugin/divide/handler/DividePluginDataHandler.java b/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/main/java/org/apache/shenyu/plugin/divide/handler/DividePluginDataHandler.java index 95e2929ab1c7..5681f38ecc92 100644 --- a/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/main/java/org/apache/shenyu/plugin/divide/handler/DividePluginDataHandler.java +++ b/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/main/java/org/apache/shenyu/plugin/divide/handler/DividePluginDataHandler.java @@ -18,6 +18,10 @@ package org.apache.shenyu.plugin.divide.handler; import org.apache.shenyu.common.constant.Constants; +import org.apache.shenyu.common.config.contract.ConfigurationContractRegistry; +import org.apache.shenyu.common.config.contract.ConfigurationScope; +import org.apache.shenyu.common.config.contract.ConfigurationValidation; +import org.apache.shenyu.common.config.contract.ConfigurationValidationException; import org.apache.shenyu.common.dto.RuleData; import org.apache.shenyu.common.dto.SelectorData; import org.apache.shenyu.common.dto.convert.rule.canary.CanaryConfigValidator; @@ -66,10 +70,18 @@ public void removeSelector(final SelectorData selectorData) { @Override public void handlerRule(final RuleData ruleData) { Optional.ofNullable(ruleData.getHandle()).ifPresent(s -> { + ConfigurationValidation validation = ConfigurationContractRegistry.shared().validate("divide", ConfigurationScope.RULE, "1", s); + if (validation.status() == ConfigurationValidation.Status.INVALID) { + throw new ConfigurationValidationException(validation); + } DivideRuleHandle divideRuleHandle = CanaryConfigValidator.parseHandle(s); if (Objects.nonNull(divideRuleHandle.getCanary())) { - CanaryConfigValidator.validateExtensions(divideRuleHandle.getCanary(), - ParameterDataFactory::newInstance, PredicateJudgeFactory::newInstance); + try { + CanaryConfigValidator.validateExtensions(divideRuleHandle.getCanary(), + ParameterDataFactory::newInstance, PredicateJudgeFactory::newInstance); + } catch (RuntimeException error) { + throw ConfigurationValidationException.bindingUnavailable("divide", ConfigurationScope.RULE, "canary"); + } } CACHED_HANDLE.get().cachedHandle(CacheKeyUtils.INST.getKey(ruleData), divideRuleHandle); // the update is also need to clean, but there is no way to diff --git a/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/test/java/org/apache/shenyu/plugin/divide/handler/DivideContractCompatibilityTest.java b/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/test/java/org/apache/shenyu/plugin/divide/handler/DivideContractCompatibilityTest.java new file mode 100644 index 000000000000..8c0707817709 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-proxy/shenyu-plugin-divide/src/test/java/org/apache/shenyu/plugin/divide/handler/DivideContractCompatibilityTest.java @@ -0,0 +1,96 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.shenyu.plugin.divide.handler; + +import org.apache.shenyu.common.config.contract.ConfigurationValidationException; +import org.apache.shenyu.common.dto.RuleData; +import org.apache.shenyu.common.dto.convert.rule.canary.CanaryConfigValidator; +import org.apache.shenyu.common.dto.convert.rule.impl.DivideRuleHandle; +import org.apache.shenyu.common.utils.GsonUtils; +import org.apache.shenyu.plugin.base.utils.CacheKeyUtils; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class DivideContractCompatibilityTest { + + @ParameterizedTest(name = "{0}") + @MethodSource("fixtures") + void canonicalFixturesPreserveCandidateAndRemovalOwnership(final String name, final String action, final String source, + final String path, final String code) { + final DividePluginDataHandler handler = new DividePluginDataHandler(); + RuleData rule = new RuleData(); + rule.setSelectorId("contract-divide"); + rule.setId(name); + rule.setHandle("{\"timeout\":5000}"); + handler.handlerRule(rule); + String key = CacheKeyUtils.INST.getKey(rule); + final DivideRuleHandle previous = DividePluginDataHandler.CACHED_HANDLE.get().obtainHandle(key); + rule.setHandle(source); + try { + if ("REJECT_RETAIN".equals(action) || "BINDING_RETAIN".equals(action)) { + ConfigurationValidationException error = assertThrows(ConfigurationValidationException.class, () -> handler.handlerRule(rule)); + assertEquals(path, error.validation().violations().get(0).path()); + assertEquals(code, error.validation().violations().get(0).code().name()); + assertFalse(error.getMessage().contains("contract-missing")); + } else if ("THROW_RETAIN".equals(action)) { + assertThrows(IllegalArgumentException.class, () -> handler.handlerRule(rule)); + } else { + handler.handlerRule(rule); + } + final DivideRuleHandle active = DividePluginDataHandler.CACHED_HANDLE.get().obtainHandle(key); + assertNotNull(active); + if ("REPLACE".equals(action)) { + assertNotSame(previous, active); + assertEquals(GsonUtils.getInstance().toJson(CanaryConfigValidator.parseHandle(source)), GsonUtils.getInstance().toJson(active)); + } else { + assertSame(previous, active); + } + // Characterize the existing conditional removal; schema adoption must not strengthen it silently. + rule.setHandle(null); + handler.removeRule(rule); + assertSame(active, DividePluginDataHandler.CACHED_HANDLE.get().obtainHandle(key)); + rule.setHandle("{}"); + handler.removeRule(rule); + handler.removeRule(rule); + assertNull(DividePluginDataHandler.CACHED_HANDLE.get().obtainHandle(key)); + } finally { + rule.setHandle("{}"); + handler.removeRule(rule); + } + } + + private static java.util.stream.Stream fixtures() throws java.io.IOException { + try (var input = java.util.Objects.requireNonNull(DivideContractCompatibilityTest.class.getResourceAsStream( + "/META-INF/shenyu/config-contract-fixtures/divide-rule-v1.tsv")); + var reader = new java.io.BufferedReader(new java.io.InputStreamReader(input, java.nio.charset.StandardCharsets.UTF_8))) { + return reader.lines().filter(line -> !line.isBlank() && !line.startsWith("#")).map(line -> { + String[] fields = line.split("\\t", -1); + String source = "@missing".equals(fields[4]) ? null : "@blank".equals(fields[4]) ? "" : fields[4]; + return org.junit.jupiter.params.provider.Arguments.of(fields[0], fields[3], source, fields[5], fields[6]); + }).toList().stream(); + } + } +} diff --git a/shenyu-plugin/shenyu-plugin-rewrite/src/main/java/org/apache/shenyu/plugin/rewrite/handler/RewritePluginDataHandler.java b/shenyu-plugin/shenyu-plugin-rewrite/src/main/java/org/apache/shenyu/plugin/rewrite/handler/RewritePluginDataHandler.java index 8d6d30fc49a9..016672c7f1ed 100644 --- a/shenyu-plugin/shenyu-plugin-rewrite/src/main/java/org/apache/shenyu/plugin/rewrite/handler/RewritePluginDataHandler.java +++ b/shenyu-plugin/shenyu-plugin-rewrite/src/main/java/org/apache/shenyu/plugin/rewrite/handler/RewritePluginDataHandler.java @@ -22,7 +22,9 @@ import org.apache.shenyu.common.dto.convert.rule.RewriteHandle; import org.apache.shenyu.common.enums.PluginEnum; import org.apache.shenyu.common.utils.GsonUtils; -import org.apache.shenyu.common.utils.RewriteHandleUtils; +import org.apache.shenyu.common.config.contract.ConfigurationContractRegistry; +import org.apache.shenyu.common.config.contract.ConfigurationScope; +import org.apache.shenyu.common.config.contract.ConfigurationValidation; import org.apache.shenyu.plugin.base.cache.CommonHandleCache; import org.apache.shenyu.plugin.base.handler.PluginDataHandler; import org.apache.shenyu.plugin.base.utils.BeanHolder; @@ -51,7 +53,7 @@ public void handlerRule(final RuleData ruleData) { return; } final RewriteHandle rewriteHandle = GsonUtils.getInstance().fromJson(handle, RewriteHandle.class); - if (Objects.isNull(rewriteHandle) || !canRewrite(rewriteHandle, ruleData)) { + if (Objects.isNull(rewriteHandle) || !canRewrite(ruleData)) { removeRule(ruleData); return; } @@ -73,17 +75,15 @@ public String pluginNamed() { * Check whether the plugin can apply the rule handle, so that an unusable rule is * rejected when it is published instead of failing every matching request. * - * @param rewriteHandle the parsed rule handle * @param ruleData the rule that owns the handle * @return true when the plugin can apply the handle */ - private static boolean canRewrite(final RewriteHandle rewriteHandle, final RuleData ruleData) { - final String problem = RewriteHandleUtils.applicabilityProblem(rewriteHandle.getRegex(), rewriteHandle.getReplace()); - if (Objects.isNull(problem)) { + private static boolean canRewrite(final RuleData ruleData) { + ConfigurationValidation result = ConfigurationContractRegistry.shared().validate("rewrite", ConfigurationScope.RULE, "1", ruleData.getHandle()); + if (result.status() == ConfigurationValidation.Status.VALID) { return true; } - LOG.error("invalid rewrite rule [{}] is ignored, regex: {}, replace: {}, reason: {}", - ruleData.getId(), rewriteHandle.getRegex(), rewriteHandle.getReplace(), problem); + LOG.error("invalid rewrite rule [{}] is ignored, reason: {}", ruleData.getId(), result.violations()); return false; } } diff --git a/shenyu-plugin/shenyu-plugin-rewrite/src/test/java/org/apache/shenyu/plugin/rewrite/RewriteContractCompatibilityTest.java b/shenyu-plugin/shenyu-plugin-rewrite/src/test/java/org/apache/shenyu/plugin/rewrite/RewriteContractCompatibilityTest.java new file mode 100644 index 000000000000..8a3cb30473a7 --- /dev/null +++ b/shenyu-plugin/shenyu-plugin-rewrite/src/test/java/org/apache/shenyu/plugin/rewrite/RewriteContractCompatibilityTest.java @@ -0,0 +1,117 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 org.apache.shenyu.plugin.rewrite; + +import org.apache.shenyu.common.constant.Constants; +import org.apache.shenyu.common.dto.MetaData; +import org.apache.shenyu.common.dto.RuleData; +import org.apache.shenyu.common.dto.SelectorData; +import org.apache.shenyu.common.dto.convert.rule.RewriteHandle; +import org.apache.shenyu.plugin.api.context.ShenyuContext; +import org.apache.shenyu.plugin.base.cache.MetaDataCache; +import org.apache.shenyu.plugin.base.utils.CacheKeyUtils; +import org.apache.shenyu.plugin.rewrite.handler.RewritePluginDataHandler; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.mock.http.server.reactive.MockServerHttpRequest; +import org.springframework.mock.web.server.MockServerWebExchange; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class RewriteContractCompatibilityTest { + + @ParameterizedTest(name = "{0}") + @MethodSource("fixtures") + void sharedFixturesCoverPublicationAndRuntime(final String name, final String action, final String source, + final String path, final String rewritten, final String metadata, final String contextPath) { + final RewritePluginDataHandler handler = new RewritePluginDataHandler(); + RuleData rule = new RuleData(); + rule.setSelectorId("contract-selector"); + rule.setId(name); + rule.setHandle("{\"regex\":\"/old\",\"replace\":\"/new\"}"); + handler.handlerRule(rule); + String key = CacheKeyUtils.INST.getKey(rule); + final RewriteHandle previous = RewritePluginDataHandler.CACHED_HANDLE.get().obtainHandle(key); + rule.setHandle(source); + try { + if ("THROW_RETAIN".equals(action)) { + assertThrows(RuntimeException.class, () -> handler.handlerRule(rule)); + } else { + handler.handlerRule(rule); + } + RewriteHandle current = RewritePluginDataHandler.CACHED_HANDLE.get().obtainHandle(key); + if ("RETAIN".equals(action) || "THROW_RETAIN".equals(action)) { + assertSame(previous, current); + } else if ("REPLACE".equals(action)) { + assertNotNull(current); + assertNotSame(previous, current); + } else { + assertNull(current); + } + MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(path).build()); + ShenyuContext context = new ShenyuContext(); + context.setRpcType("http"); + exchange.getAttributes().put(Constants.CONTEXT, context); + String prefix = "@missing".equals(contextPath) ? "" : contextPath; + context.setRealUrl(prefix.isEmpty() ? path : path.substring(prefix.length())); + if (!prefix.isEmpty()) { + exchange.getAttributes().put(Constants.CONTEXT_PATH, prefix); + } + if ("enabled".equals(metadata) || "disabled".equals(metadata)) { + String metadataPath = prefix + rewritten; + MetaData data = MetaData.builder().id("contract-meta").path(metadataPath).rpcType("dubbo").enabled("enabled".equals(metadata)).build(); + MetaDataCache.getInstance().initCache(metadataPath, data, metadataPath); + } + AtomicInteger continued = new AtomicInteger(); + StepVerifier.create(new RewritePlugin().doExecute(exchange, next -> { + continued.incrementAndGet(); + return Mono.empty(); + }, new SelectorData(), rule)).verifyComplete(); + assertEquals(1, continued.get()); + assertEquals("@none".equals(rewritten) ? null : rewritten, exchange.getAttribute(Constants.REWRITE_URI)); + assertEquals("enabled".equals(metadata) ? "dubbo" : "http", context.getRpcType()); + handler.removeRule(rule); + handler.removeRule(rule); + assertNull(RewritePluginDataHandler.CACHED_HANDLE.get().obtainHandle(key)); + } finally { + handler.removeRule(rule); + MetaDataCache.getInstance().clean(); + } + } + + private static java.util.stream.Stream fixtures() throws java.io.IOException { + try (var input = java.util.Objects.requireNonNull(RewriteContractCompatibilityTest.class.getResourceAsStream( + "/META-INF/shenyu/config-contract-fixtures/rewrite-rule-v1.tsv")); + var reader = new java.io.BufferedReader(new java.io.InputStreamReader(input, java.nio.charset.StandardCharsets.UTF_8))) { + return reader.lines().filter(line -> !line.isBlank() && !line.startsWith("#")).map(line -> { + String[] fields = line.split("\\t", -1); + String source = "@missing".equals(fields[3]) ? null : "@blank".equals(fields[3]) ? "" : fields[3]; + return org.junit.jupiter.params.provider.Arguments.of(fields[0], fields[2], source, fields[4], fields[5], fields[6], fields[7]); + }).toList().stream(); + } + } +}