Skip to content

fix(divide): account for header names and framing in headerMaxSize (#… - #7821

Merged
yuluo-yx merged 2 commits into
apache:masterfrom
harshkha3417:fix/7818-divide-header-max-size
Oct 24, 2026
Merged

yuluo-yx merged 2 commits into
apache:masterfrom
harshkha3417:fix/7818-divide-header-max-size

Conversation

@harshkha3417

Copy link
Copy Markdown
Contributor

Fixes #7818.

Motivation

In DividePlugin, headerMaxSize previously summed only the byte lengths of request header values:

long headerSize = exchange.getRequest().getHeaders().values()
        .stream()
        .flatMap(Collection::stream)
        .mapToLong(header -> header.getBytes(StandardCharsets.UTF_8).length)
        .sum();

Aias00
Aias00 previously approved these changes Oct 19, 2026

@Aias00 Aias00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved. Including the field names and the ": " / CRLF framing closes a real gap: the previous sum only covered values, so a request could carry arbitrarily long header names — or many empty-valued headers — without ever approaching headerMaxSize. Counting name + value + 4 per line plus the terminating CRLF is the right model, and the boundary tests (> max rejects, == max allows) pin the semantics precisely, which is the part that usually drifts.

The empty and null branches are correct: a header with an empty value list still costs name + 4, and the early return for a null or empty map avoids reporting the 2-byte terminator for a request that never had a header section.

Three notes, none blocking:

  1. Multi-valued headers are over-counted, deliberately conservative. Spring keeps Accept: text/html, application/json either as two entries or as one entry with two values depending on the inbound codec; counting each value as its own name: value\r\n line charges the name twice when the client actually sent one comma-joined line. That errs toward rejecting, never toward bypassing, so it is the safe direction — just be aware that a request sitting within a few bytes of the limit may be rejected on one path and accepted on the other.

  2. Byte length uses UTF-8 while the wire is ISO-8859-1 for HTTP/1.1 header values. For any character above U+007F that over-counts (2 or 3 bytes instead of 1), again conservative. If you want exactness per protocol you would need to know whether the request arrived over HTTP/1.1 or HTTP/2 (HPACK, UTF-8), which is not worth the complexity — worth a one-line comment so the next reader does not “fix” it.

  3. Merge-order conflict with #7820. Both PRs edit the same block:

if (ruleHandle.getHeaderMaxSize() > 0) {
    long headerSize = calculateHeaderSize(exchange.getRequest().getHeaders());
    ...
}

#7820 rewrites that stanza to read from effectiveExchange (the chunked-body decorator) and touches the neighbouring requestMaxSize check. Whichever lands second will need a rebase — the two changes are compatible, they just overlap textually. Worth coordinating so one of you rebases rather than letting it auto-merge blindly.

calculateHeaderSize being package-private for the direct unit tests is a reasonable trade here, and the arithmetic in the test comments matches the implementation exactly, which makes the tests readable as a specification.

CI has not reported on this branch yet — please confirm the workflow passes before merge.

@harshkha3417

Copy link
Copy Markdown
Contributor Author

Thanks @Aias00 for the thorough review and approval!

  1. Rebase & master alignment: Rebased the branch on the latest master. It applies cleanly without conflicts.
  2. UTF-8 comment: Added an inline comment documenting that UTF-8 is used as a conservative upper bound across HTTP/1.1 and HTTP/2 without protocol branching.
  3. fix(divide): enforce requestMaxSize on chunked request bodies #7820 compatibility: Since the two changes are functionally compatible and fix(divide): account for header names and framing in headerMaxSize (#… #7821 is approved, if fix(divide): account for header names and framing in headerMaxSize (#… #7821 lands first, fix(divide): enforce requestMaxSize on chunked request bodies #7820 can trivially rebase and retain calculateHeaderSize(effectiveExchange.getRequest().getHeaders()).

@harshkha3417
harshkha3417 requested a review from Aias00 October 19, 2026 03:06
Aias00
Aias00 previously approved these changes Oct 19, 2026

@Aias00 Aias00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-approving after the follow-up push (which dismissed the previous approval).

The delta is a single comment, and it addresses exactly the point I raised:

// Uses UTF-8 byte counting conservatively across HTTP/1.1 and HTTP/2 without protocol branching.

That documents the deliberate choice — UTF-8 over-counts non-ASCII header bytes relative to HTTP/1.1’s ISO-8859-1 and under-counts relative to HPACK’s Huffman coding, so it errs toward rejecting rather than toward bypassing, and avoids branching on protocol. Recording it in the code is better than leaving the next reader to rediscover it, which was the whole point of the note.

Nothing else changed: the name + value + 4 accounting, the terminating CRLF, the >= 0 boundary semantics and the parameterized tests are all as reviewed. My earlier remarks about multi-value headers being over-counted and about the textual overlap with #7820 both still apply and are both non-blocking.

Good to merge once #7820 or this one rebases — whichever lands second.

Aias00
Aias00 previously approved these changes Oct 21, 2026

@Aias00 Aias00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: account for header names and framing in headerMaxSize

Reviewed the delta on top of the two revisions I approved earlier. The fix is correct and the added tests are good — approving.

What changed and why it is right

headerMaxSize previously summed only the values (headers.values().stream().flatMap(...)), which under-counts the real wire size of the header field section by every header name plus the ": " separator and the CRLF of each line. The new calculateHeaderSize counts nameSize + valueSize + 4 per header line (4 = ": " + CRLF) and adds the terminating CRLF, which matches the actual serialized form:

  • multi-valued header → one line per value, counted separately (correct: that is how they were parsed off the wire)
  • empty value list → nameSize + 4, i.e. Name: \r\n (correct)
  • null element in the value list → treated as 0-length value (correct, and defensive)

I checked the arithmetic in every added assertion and it holds (Host: 127.0.0.1 = 4+9+4 = 17, the 202-char name with empty value = 202+0+4 = 206, +2 terminating CRLF = 225, etc.). Replacing the stream with a plain loop also removes the per-element lambda/Collection::stream allocation on a hot path, which is a small bonus.

The boundary test is the valuable one here: 18 rejects / 19 accepts / 20 accepts against a 19-byte request pins the > (not >=) comparison, so an off-by-one in either the counter or the comparison would now fail loudly.

CI

pr_build and build (shenyu-integrated-test-http) both pass, including the headerMaxSize: 10240 divide rule in shenyu-integrated-test-http/.../DividePluginTest, which is the only place in the repo that actually configures this field.

build (shenyu-integrated-test-sdk-http) failed, but it is not this PR:

SdkHttpIntegratedTest.testFindById:38 expected: <sdk-currentToken> but was: <null>
SdkHttpIntegratedTest.testSdkAnno:48  expected: <name=shenyu-sdk,Cookie=cookie,header=header> but was: <null>
[INFO]   Run 1: PASS
[ERROR]  Run 2: ... <null>

Run 1: PASS / Run 2: FAILURE on the same JVM is the flaky-rerun signature, and the causal link is absent anyway: DivideRuleHandle.headerMaxSize is a long defaulting to 0, so if (ruleHandle.getHeaderMaxSize() > 0) short-circuits and calculateHeaderSize is never called. The sdk-http module never sets the field (it is only set in the http IT). Could you push an empty commit or re-run that job so the suite goes green? Nothing to change in the diff.

Non-blocking

  1. This silently tightens the effective limit for existing deployments. Anyone who tuned headerMaxSize against the old values-only counting will now see requests rejected a few hundred bytes earlier, because names and framing are included. That is the intended fix, but it is a user-visible semantic change — worth a line in RELEASE-NOTES.md / the headerMaxSize doc so operators are not surprised.

  2. The request line and HTTP/2 pseudo-headers are not counted. GET /path HTTP/1.1 and :method / :path / :authority / :scheme are part of the header block on the wire but are not in HttpHeaders. The javadoc is careful to say "header field section", which is accurate — just make sure nobody reads headerMaxSize as "total request line + headers" later. The request line is covered by requestMaxSize in #7820.

  3. Empty-vs-non-empty asymmetry: calculateHeaderSize(new HttpHeaders()) returns 0, while the documented rule ("plus the terminating CRLF of the HTTP header section") would give 2. Harmless because the caller only compares against a positive threshold, but if you want the function to be self-consistently documented, returning 2L for an empty header block is the more literal answer.

  4. StringUtils.defaultString(entry.getKey()) — HttpHeaders keys are never null, so this is dead defensiveness; fine to keep, just noting it.

@harshkha3417

Copy link
Copy Markdown
Contributor Author

Thanks @Aias00 for the thorough review and explanation regarding the flaky shenyu-integrated-test-sdk-http run!

I have addressed all non-blocking observations:

  1. Release Notes Documentation: Documented the headerMaxSize calculation change under Behavior Changes in RELEASE-NOTES.md so operators with tight limits are aware of the wire-accurate counting.
  2. Javadoc Clarification: Clarified that calculateHeaderSize measures the header field section (excluding request line / pseudo-headers) and explicitly returns 0L for null/empty headers.
  3. Defensive Cleanup: Removed redundant StringUtils.defaultString on the non-null HttpHeaders map keys.
  4. Pushed updates to trigger a clean CI workflow run.

@harshkha3417
harshkha3417 requested a review from Aias00 October 22, 2026 01:23
Aias00
Aias00 previously approved these changes Oct 22, 2026

@Aias00 Aias00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review: #7821 fix(divide): account for header names and framing in headerMaxSize

Verdict: approved — the follow-up commit addresses exactly the two gaps I raised (release note and the measurement's documented scope), and tightens the size computation.

What changed since my approval

  1. RELEASE-NOTES.md now documents the behaviour change. The new Behavior Changes entry states that headerMaxSize counts the whole header field section (names, values, ": ", CRLF, terminating CRLF) instead of values only, and warns that deployments sitting near a strict limit may start seeing rejections. That was the one item I called out as missing, and the wording is accurate — it does not undersell how much the effective limit tightens.
  2. The Javadoc now declares what is not measured. calculateHeaderSize documents that it covers the header field section and excludes the request line and HTTP/2 pseudo-headers. That closes the second gap: the old boundary tests all sat comfortably away from these edge cases, so the omission was invisible from the test suite.
  3. StringUtils.defaultString(entry.getKey()) reduced to entry.getKey(). Safe: HttpHeaders key lookups go through a case-insensitive map that rejects null keys (set(null, ...) throws), so an entry can never carry a null name. Removing the fallback makes the assumption explicit rather than hiding it.

Re-verified

  • The per-line accounting is name + value + 4 (": " and CRLF) with a single trailing + 2 for the section terminator — so an empty value still costs name + 4, which matches how HTTP/1.1 renders Name: \r\n. The Collections.emptyList() branch adds the same name + 4, keeping a valueless header from being free.
  • Null values are counted as zero bytes rather than throwing, and testCalculateHeaderSizeWithEmptyValuesListAndNullValue pins that (23L).
  • testDoExecuteHeaderMaxSizeRejectsLongHeaderNameWithEmptyValue is the case the original code got wrong: a 200-character name with an empty value contributed 0 before and 206 now, so 225 > 128 rejects and verify(testChain, never()).execute(...) proves the request never reaches the chain.
  • calculateHeaderSize is package-private, which is what lets DividePluginTest assert exact byte counts instead of going through a mocked exchange.
  • Boundary arithmetic in the tests is self-documenting (4 + 2 + 9 + 2 = 17 etc.), so the expected values can be re-derived without trusting the implementation.

Only the skipping path-filtered jobs are non-green; the build and unit suites pass.

@harshkha3417

Copy link
Copy Markdown
Contributor Author

/retest

@Aias00

Aias00 commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

Approved, but there are two things to handle before this can land.

1. Merge conflict — mergeable_state is dirty, so this needs a rebase onto current master.

2. Shared e2e failure — after rebasing you will still see build (shenyu-integrated-test-http) red, but it is not your change:

[ERROR] CachePluginTest.testMemoryModle:54 expected: <true> but was: <false>
[ERROR] CachePluginTest.testRedisModle:73  expected: <true> but was: <false>

That case is red across every PR touching this module right now. Ping me once it is rebased and I will take another look.

@yuluo-yx

Copy link
Copy Markdown
Member

hi @harshkha3417 please resolve conflicts, thanks

/retest
/hold

@yuluo-yx yuluo-yx added the hold On hold, do not merge label Oct 24, 2026
@harshkha3417
harshkha3417 force-pushed the fix/7818-divide-header-max-size branch from 4173d20 to 2d7851c Compare October 24, 2026 03:51
@harshkha3417
harshkha3417 force-pushed the fix/7818-divide-header-max-size branch from 2d7851c to b4c3a26 Compare October 24, 2026 03:54
@harshkha3417

Copy link
Copy Markdown
Contributor Author

@yuluo-yx Conflicts had been resolved.
Thanks.

@harshkha3417
harshkha3417 requested a review from Aias00 October 24, 2026 04:06
@yuluo-yx

Copy link
Copy Markdown
Member

/lgtm

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved via /lgtm by @yuluo-yx.

@yuluo-yx yuluo-yx removed the hold On hold, do not merge label Oct 24, 2026
@yuluo-yx
yuluo-yx merged commit 7e5a1e7 into apache:master Oct 24, 2026
29 checks passed
dmsolr pushed a commit that referenced this pull request Oct 25, 2026
Sync to current master to resolve the stable shenyu-integrated-test-http CI failure (CachePluginTest.testMemoryModle/testRedisModle). Root cause: this branch predated #8079, whose pre-fix CachedResponse.capture() refused to store any response carrying a Vary header, so the cached endpoint was never reused and both requests hit the backend. #8079 keys Vary responses on the selecting request headers instead. Also pulls in the divide/loadbalancer work (#8076, #7172, #7986, #8005, #7821, #8033, #8090).

#7172 removeStaleUpstreams reconciles via removeFromMap/triggerRemoveOne, which republish the immutable healthy snapshot under the same lock, so the read-only snapshot model stays correct with no stale retained instances.
@Aias00 Aias00 added this to the 2.7.2 milestone Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Divide headerMaxSize counts only values and omits header names

4 participants