Skip to content

Commit 947c216

Browse files
committed
[ISSUE #8037] Reject sticky values that silently disable affinity or read the wrong location
1 parent 188ebcf commit 947c216

10 files changed

Lines changed: 349 additions & 48 deletions

File tree

‎RELEASE-NOTES.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,20 @@
217217
aggregate and remains an explicit choice. See `shenyu-registry/README.md` for the
218218
provider table and migration steps. (#7578)
219219

220+
- The admin now validates the `sticky` section of a divide rule handle when a rule is
221+
saved: `onUnavailable` must be exactly `REBIND` or `STRICT`, `maxAgeSeconds` must be
222+
positive, `cookieName` must be a non-blank string (an explicit `null` is not accepted
223+
as a substitute for omitting it), an enabled configuration needs at least one non-blank
224+
`secrets` entry, and a configured deterministic `key` needs a non-blank `name` and,
225+
when `type` is present, `HEADER` or `COOKIE`. JSON structure is checked before Gson can
226+
coerce values, so a non-object `sticky`, a non-integer lifetime, a non-array secret
227+
list or a non-string field is rejected with a `sticky.…` field error. A disabled
228+
(`enabled=false`) sticky section is exempt from value validation, because the gateway
229+
activation checks ignore it and its values cannot affect a request, so an unrelated
230+
field of an already stored rule stays editable; structural type checks still apply.
231+
The gateway runtime stays tolerant for values: a configuration persisted before this
232+
validation still degrades to plain load balancing instead of failing requests. (#8037)
233+
220234
## [v2.7.0]- 2024-12-23
221235

222236
### ✨ New Features

‎docs/divide-sticky-session-affinity.md‎

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -95,18 +95,25 @@ naming the offending field (`sticky.…`):
9595
policy case-sensitively, so any other spelling (including `strict`) would silently
9696
behave as `REBIND` and is rejected instead.
9797
- `maxAgeSeconds` must be a positive number.
98-
- `cookieName` must not be blank; omit it to use the rule-scoped default.
98+
- `cookieName` must be a non-blank string; omit it to use the rule-scoped default.
99+
An explicit JSON `null` is rejected as well: it is not equivalent to omitting the
100+
field and would silently disable affinity.
99101
- An enabled configuration requires at least one non-blank key in `secrets`.
100-
- A configured `key` (deterministic key) requires a non-blank `name`.
101-
102-
A disabled configuration is not validated: the runtime activation checks ignore it
103-
entirely, so none of its values can affect a request. Rejecting it would stop an
104-
operator from editing an unrelated field of an already stored rule.
105-
106-
The gateway runtime itself stays tolerant: a malformed configuration that was
107-
persisted before this validation (or edited directly in the store) degrades to
108-
plain load balancing through the runtime activation checks, so an upgrade never
109-
turns a stored bad rule into a request failure.
102+
- A configured `key` (deterministic key) requires a non-blank `name`, and its
103+
`type`, when present, must be `HEADER` or `COOKIE`. Gson maps an unknown spelling
104+
to `null`, and the extractor then reads a request header, so `"type":"cookie"` is
105+
rejected instead of silently reading the wrong request location.
106+
107+
JSON structure is checked before Gson can coerce values, so a sticky section that is
108+
not an object, a non-integer `maxAgeSeconds`, a non-array `secrets` or a non-string
109+
field fails with a `sticky.…` message instead of the generic `Invalid Divide handle
110+
JSON`. These structural checks also apply to a disabled section, because those shapes
111+
cannot be bound at all; the disabled exemption covers value validation only.
112+
113+
The gateway runtime keeps its tolerance for values: a semantically unusable
114+
configuration that was persisted before this validation (or edited directly in the
115+
store) degrades to plain load balancing through the runtime activation checks.
116+
Structural JSON type errors are rejected when the handle is parsed, as before.
110117

111118
## Cross-replica operation
112119

‎shenyu-admin/src/main/java/org/apache/shenyu/admin/service/impl/RuleServiceImpl.java‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ public String registerDefault(final RuleDTO ruleDTO) {
171171
return "";
172172
}
173173
validateRuleHandle(ruleDTO);
174-
validateDivideHandle(ruleDTO.getSelectorId(), ruleDTO.getHandle());
174+
validateCanaryAndStickyConfig(ruleDTO.getSelectorId(), ruleDTO.getHandle());
175175
RuleDO ruleDO = RuleDO.buildRuleDO(ruleDTO);
176176
if (StringUtils.isEmpty(ruleDTO.getId())) {
177177
ruleMapper.insertSelective(ruleDO);
@@ -197,7 +197,7 @@ public int createOrUpdate(final RuleDTO ruleDTO) {
197197
@Override
198198
public int create(final RuleDTO ruleDTO) {
199199
validateRuleHandle(ruleDTO);
200-
validateDivideHandle(ruleDTO.getSelectorId(), ruleDTO.getHandle());
200+
validateCanaryAndStickyConfig(ruleDTO.getSelectorId(), ruleDTO.getHandle());
201201
RuleDO ruleDO = RuleDO.buildRuleDO(ruleDTO);
202202
final int ruleCount = ruleMapper.insertSelective(ruleDO);
203203
addCondition(ruleDO, ruleDTO.getRuleConditions());
@@ -212,7 +212,7 @@ public int update(final RuleDTO ruleDTO) {
212212
validateRuleHandle(ruleDTO);
213213
final RuleDO before = ruleMapper.selectById(ruleDTO.getId());
214214
Assert.notNull(before, "the updated rule is not found");
215-
validateDivideHandle(StringUtils.defaultIfBlank(ruleDTO.getSelectorId(), before.getSelectorId()), ruleDTO.getHandle());
215+
validateCanaryAndStickyConfig(StringUtils.defaultIfBlank(ruleDTO.getSelectorId(), before.getSelectorId()), ruleDTO.getHandle());
216216
RuleDO ruleDO = RuleDO.buildRuleDO(ruleDTO);
217217
final int ruleCount = ruleMapper.updateSelective(ruleDO);
218218

@@ -248,7 +248,7 @@ public int update(final RuleDTO ruleDTO) {
248248
return ruleCount;
249249
}
250250

251-
private void validateDivideHandle(final String selectorId, final String handle) {
251+
private void validateCanaryAndStickyConfig(final String selectorId, final String handle) {
252252
if (StringUtils.isBlank(handle)) {
253253
return;
254254
}
@@ -262,13 +262,11 @@ private void validateDivideHandle(final String selectorId, final String handle)
262262
}
263263
try {
264264
DivideRuleHandle divide = CanaryConfigValidator.parseHandle(handle);
265-
if (Objects.nonNull(divide) && Objects.nonNull(divide.getCanary())) {
265+
if (Objects.nonNull(divide.getCanary())) {
266266
CanaryConfigValidator.validateExtensions(divide.getCanary(),
267267
name -> validateCanaryDictionary("paramType", name), name -> validateCanaryDictionary("operator", name));
268268
}
269-
if (Objects.nonNull(divide)) {
270-
StickySessionConfigValidator.validate(divide.getSticky());
271-
}
269+
StickySessionConfigValidator.validate(divide.getSticky());
272270
} catch (IllegalArgumentException ex) {
273271
throw new ShenyuAdminException(ex.getMessage(), ex);
274272
}
@@ -365,7 +363,7 @@ public ConfigImportResult importData(final List<RuleDTO> ruleList) {
365363
return ConfigImportResult.success();
366364
}
367365

368-
ruleList.forEach(rule -> validateDivideHandle(rule.getSelectorId(), rule.getHandle()));
366+
ruleList.forEach(rule -> validateCanaryAndStickyConfig(rule.getSelectorId(), rule.getHandle()));
369367
Map<String, List<RuleDO>> selectorRuleMap = ruleMapper
370368
.selectAll()
371369
.stream()
@@ -412,7 +410,7 @@ public ConfigImportResult importData(final String namespace, final List<RuleDTO>
412410
}
413411
Map<String, String> selectorIdMapping = context.getSelectorIdMapping();
414412
ruleList.stream().filter(rule -> selectorIdMapping.containsKey(rule.getSelectorId()))
415-
.forEach(rule -> validateDivideHandle(selectorIdMapping.get(rule.getSelectorId()), rule.getHandle()));
413+
.forEach(rule -> validateCanaryAndStickyConfig(selectorIdMapping.get(rule.getSelectorId()), rule.getHandle()));
416414
Map<String, Set<String>> selectorRuleMap = ruleMapper
417415
.selectAllByNamespaceId(namespace)
418416
.stream()

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

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -735,7 +735,11 @@ public void testCanaryFailoverNeverWritesOrPublishes() {
735735
"{\"enabled\":true,\"secrets\":[\"secret\"],\"maxAgeSeconds\":0}",
736736
"{\"enabled\":true,\"secrets\":[]}",
737737
"{\"enabled\":true,\"secrets\":[\"secret\"],\"cookieName\":\" \"}",
738-
"{\"enabled\":true,\"secrets\":[\"secret\"],\"key\":{}}"})
738+
"{\"enabled\":true,\"secrets\":[\"secret\"],\"cookieName\":null}",
739+
"{\"enabled\":true,\"secrets\":[\"secret\"],\"key\":{}}",
740+
"{\"enabled\":true,\"secrets\":[\"secret\"],\"key\":{\"name\":\"X\",\"type\":\"cookie\"}}",
741+
"{\"enabled\":true,\"secrets\":\"s\"}",
742+
"{\"enabled\":true,\"maxAgeSeconds\":1.5}"})
739743
public void testInvalidStickyNeverWritesOrPublishes(final String stickyPatch) {
740744
configureDivideSelector();
741745
RuleDTO dto = buildRuleDTO("");
@@ -745,11 +749,34 @@ public void testInvalidStickyNeverWritesOrPublishes(final String stickyPatch) {
745749
given(ruleMapper.selectById("123")).willReturn(buildRuleDO("123"));
746750
assertThrows(ShenyuAdminException.class, () -> ruleService.createOrUpdate(dto));
747751
assertThrows(ShenyuAdminException.class, () -> ruleService.registerDefault(dto));
752+
assertThrows(ShenyuAdminException.class, () -> ruleService.importData(Collections.singletonList(dto)));
753+
ConfigsImportContext context = new ConfigsImportContext();
754+
context.getSelectorIdMapping().put("456", "456");
755+
assertThrows(ShenyuAdminException.class,
756+
() -> ruleService.importData(SYS_DEFAULT_NAMESPACE_ID, Collections.singletonList(dto), context));
748757
verify(ruleMapper, never()).insertSelective(any());
749758
verify(ruleMapper, never()).updateSelective(any());
750759
verifyNoInteractions(ruleConditionMapper, ruleEventPublisher);
751760
}
752761

762+
@Test
763+
public void testStickyErrorsNameTheField() {
764+
assertStickyError("{\"enabled\":true,\"secrets\":\"s\"}", "sticky.secrets must be an array");
765+
assertStickyError("{\"enabled\":true,\"secrets\":[\"secret\"],\"cookieName\":null}",
766+
"sticky.cookieName must not be blank; omit it to use the default");
767+
assertStickyError("{\"enabled\":true,\"secrets\":[\"secret\"],\"key\":{\"name\":\"X\",\"type\":\"cookie\"}}",
768+
"sticky.key.type must be HEADER or COOKIE, got: cookie");
769+
}
770+
771+
private void assertStickyError(final String stickyPatch, final String message) {
772+
configureDivideSelector();
773+
RuleDTO dto = buildRuleDTO("");
774+
dto.setHandle(stickyHandle(stickyPatch));
775+
ShenyuAdminException exception = assertThrows(ShenyuAdminException.class,
776+
() -> ruleService.createOrUpdate(dto));
777+
assertEquals(message, exception.getMessage());
778+
}
779+
753780
/**
754781
* A valid sticky section is stored unchanged, so the management plane accepts what the
755782
* runtime can execute (#8037).

‎shenyu-common/src/main/java/org/apache/shenyu/common/dto/convert/rule/canary/CanaryConfigValidator.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import org.apache.commons.lang3.StringUtils;
2626
import org.apache.shenyu.common.dto.ConditionData;
2727
import org.apache.shenyu.common.dto.convert.rule.impl.DivideRuleHandle;
28+
import org.apache.shenyu.common.dto.convert.rule.sticky.StickySessionConfigValidator;
2829
import org.apache.shenyu.common.enums.RetryEnum;
2930
import org.apache.shenyu.common.utils.DateUtils;
3031
import org.apache.shenyu.common.utils.GsonUtils;
@@ -57,6 +58,7 @@ public static DivideRuleHandle parseHandle(final String handle) {
5758
if (Objects.nonNull(canary) && !canary.isJsonNull()) {
5859
validate(object(canary, "canary"));
5960
}
61+
StickySessionConfigValidator.validateJson(root.get("sticky"));
6062
DivideRuleHandle result = GsonUtils.getInstance().fromJson(root, DivideRuleHandle.class);
6163
if (Objects.nonNull(result.getCanary()) && result.getRetry() > 0
6264
&& !RetryEnum.CURRENT.getName().equals(StringUtils.defaultIfEmpty(result.getRetryStrategy(), RetryEnum.CURRENT.getName()))) {

‎shenyu-common/src/main/java/org/apache/shenyu/common/dto/convert/rule/sticky/StickySessionConfig.java‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@
1717

1818
package org.apache.shenyu.common.dto.convert.rule.sticky;
1919

20+
import org.apache.commons.lang3.StringUtils;
21+
2022
import java.util.List;
23+
import java.util.Objects;
2124

2225
/**
2326
* Optional sticky session affinity configuration for HTTP proxying.
@@ -84,6 +87,20 @@ public class StickySessionConfig {
8487
*/
8588
private DeterministicKeyConfig key;
8689

90+
/**
91+
* Whether this configuration can actually take effect at runtime: enabled with a
92+
* positive lifetime, a non-blank cookie name and a non-empty list of non-blank keys.
93+
* This is the single owner of the activation predicate shared by the gateway affinity
94+
* layer and the management-plane validator.
95+
*
96+
* @return true when affinity applies to the request
97+
*/
98+
public boolean isUsable() {
99+
return enabled && maxAgeSeconds > 0 && StringUtils.isNotBlank(cookieName)
100+
&& Objects.nonNull(secrets) && !secrets.isEmpty()
101+
&& secrets.stream().allMatch(StringUtils::isNotBlank);
102+
}
103+
87104
/**
88105
* Whether affinity is enabled.
89106
*

0 commit comments

Comments
 (0)