Skip to content

[Fix][Zeta] Compare basic auth credentials without a timing discrepancy - #12595

Merged
davidzollo merged 7 commits into
apache:devfrom
SEPURI-SAI-KRISHNA:fix-basic-auth-constant-time
Oct 18, 2026
Merged

davidzollo merged 7 commits into
apache:devfrom
SEPURI-SAI-KRISHNA:fix-basic-auth-constant-time

Conversation

@SEPURI-SAI-KRISHNA

@SEPURI-SAI-KRISHNA SEPURI-SAI-KRISHNA commented Oct 1, 2026 •

Copy link
Copy Markdown
Collaborator

Purpose of this pull request

BasicAuthFilter compares the credentials from an incoming request against the configured ones with String.equals, joined by &&:

if (username.equals(httpConfig.getBasicAuthUsername())
        && password.equals(httpConfig.getBasicAuthPassword())) {

Two separate properties of that line are worth changing, and they are independent of each other.

String.equals returns at the first differing character, so the work it does grows with how many leading characters already match. && short-circuits, so when the username does not match, the password is never compared at all, and the amount of work the filter does separates a wrong username from a correct username with a wrong password. That is CWE-208, an observable discrepancy in a credential check.

This is hardening, not a security fix. I raised it with ASF Security first and they reviewed it and concluded it is not a vulnerability, because the published threat model treats the REST API and Web UI as inside the administrative boundary and network reachability, not Basic auth, as the security boundary. I agree with that, and I am noting it so the change is read as ordinary code quality rather than an embargoed disclosure.

The case for it is simply that the difference should not be there: the fix is small, local, and does not change which credentials are accepted.

Closes #12594

What this changes

Both comparisons are computed into locals before the branch, so neither is skipped, and each one goes through MessageDigest.isEqual on the UTF-8 bytes rather than String.equals.

MessageDigest.isEqual accumulates the difference across bytes with xor and or instead of returning at the first mismatch. I checked this against the JDK 17 bytecode rather than taking the javadoc on trust: the loop bound is the length of the first argument and there is no early return inside it. The request's own value is therefore passed first, so the number of bytes read is something the caller already knows and the length of the configured credential is not what drives it.

A credentialMatches helper carries this, with the argument-order reasoning in its javadoc so a later edit does not silently swap the arguments and reintroduce the length dependency.

Null safety

The configured credentials default to admin, but they are plain String fields and can be unset. String.equals(null) is safely false; reading bytes off a null is an NPE, which would turn a 401 into a 500. The helper therefore rejects an unset credential explicitly, and there is a test for each of the three unset combinations.

Behaviour equivalence

Every accept-or-reject decision is unchanged. Checked directly, old expression against new, on the cases that tend to be where a rewrite like this goes wrong:

provided configured before after
admin admin true true
admin root false false
s3cre s3cret (prefix) false false
s3crets s3cret (longer) false false
`` `` true true
`` admin false false
admin `` false false
é (multi-byte UTF-8) é true true
admin unset (null) false false

No option, default or public signature changes. Nothing that authenticates today stops authenticating.

Tests

BasicAuthFilterTest is new, because BasicAuthFilter had no unit test. It follows ExceptionHandlingFilterTest, the existing per-filter test sitting in the same rest/filter test package, and uses the same Mockito shape. It covers correct credentials passing the chain, wrong password, wrong username, a credential that is a proper prefix of the configured one, all three unset-credential combinations asserting no exception escapes, and authentication being disabled.

Two further cases pin rows of the equivalence table above that nothing was holding:

  • testEmptyConfiguredCredentialMatchesOnlyAnEmptyProvidedValue. An unset credential is refused by an explicit null guard, but an empty one is not the same thing: two zero-length byte arrays compare equal, so a deployment that configures an empty password accepts an empty one. That is unchanged from String.equals, and it is surprising enough to be worth stating rather than rediscovering. The test also pins that empty on one side only is refused, in both directions.
  • testMultiByteCredentialIsComparedByItsUtf8Bytes. The comparison moved to bytes, so the encoding now matters. It pins that pässwörd matches itself and is still separated from two near misses: pässwürd, which differs by one multi-byte character and therefore has the same UTF-8 length, and passwörd, which substitutes ASCII and is a byte shorter.

BasicAuthenticationIT gains two cases. Its existing negative case sends wronguser:wrongpassword, which gets both halves wrong and so cannot tell whether the password is examined once the username has already failed. The new cases send a correct username with a wrong password, and a proper prefix of both, and expect 401 from each.

An earlier version of this description flagged that the two IT cases were unverified locally, because there is no Docker on this machine, and that CI would be the first thing to execute them. CI has since run them. From the test-reports-engine-v2-it-8 artifact of run 37184991698:

BasicAuthenticationIT  Tests run: 9, Failures: 0, Errors: 0, Skipped: 0  133.583 s
  testAccessWithCorrectUsernameAndWrongPassword   14.696s
  testAccessWithPrefixOfCorrectCredentials        14.801s

Both new cases ran and passed by name on the JDK 8 leg, and engine-v2-it (11) passed outright, so that flag is closed.

What the tests do and do not catch

Stating this rather than leaving it to be discovered, because it is the honest shape of a behaviour-preserving change.

Reverting this patch entirely, back to String.equals joined by &&, leaves all eight unit tests passing. I re-ran that mutation after adding the two cases above rather than carrying the old number forward. That is the expected result: the accept-or-reject decisions are identical either way, so no black-box test can separate the two implementations. A timing assertion could in principle, but it would be flaky on CI and would not earn its place, so there is not one here.

What the tests do catch is the risk this rewrite actually introduces. Removing the null guard while keeping the byte comparison fails testUnsetCredentialIsRejectedAndDoesNotThrow with exactly the regression it exists to prevent:

java.lang.NullPointerException: Cannot invoke "String.getBytes(java.nio.charset.Charset)"
because "expected" is null

Full mutation matrix, all four run against the eight tests:

mutation tests that fail
revert entirely to String.equals joined by && none, as explained above
drop the null guard, keep the byte comparison 1: testUnsetCredentialIsRejectedAndDoesNotThrow
encode the configured side as ISO_8859_1 while the request side stays UTF-8 1, alone: testMultiByteCredentialIsComparedByItsUtf8Bytes
guard also rejects an empty configured credential 1, alone: testEmptyConfiguredCredentialMatchesOnlyAnEmptyProvidedValue

So the suite is a regression guard for the rewrite, not evidence of the timing property. The timing property rests on MessageDigest.isEqual and on both comparisons being evaluated unconditionally, both of which are visible in the diff and neither of which needs a test to be checked by a reviewer. What the last two rows show is that the two new cases are not decoration: each is the only thing standing between a one-line edit and a silent behaviour change.

BasicAuthFilter compared credentials with String.equals joined by &&.
String.equals returns at the first differing character, so its cost grows
with the number of leading characters already matched, and && skipped the
password comparison entirely when the username did not match, so the work
done separated a wrong username from a correct username with a wrong
password. That is CWE-208 on the check guarding the REST API and web UI.

Compute both comparisons before branching so neither is skipped, and
compare UTF-8 bytes with MessageDigest.isEqual, which accumulates the
difference across bytes instead of returning at the first mismatch. It
reads exactly as many bytes as its first argument holds, so the request's
own value is passed first and the configured credential's length does not
drive the work. The argument order is recorded in the helper's javadoc.

The configured credentials can be unset, and String.equals(null) was
safely false, so the helper rejects a null credential explicitly rather
than turning a 401 into a 500.

Every accept-or-reject decision is unchanged, including empty values,
prefixes, longer values and multi-byte UTF-8.

Add BasicAuthFilterTest, following the existing ExceptionHandlingFilterTest
in the same package, and two BasicAuthenticationIT cases: a correct
username with a wrong password, and a proper prefix of both, neither of
which the existing wronguser:wrongpassword case could distinguish.

@DanielLeens DanielLeens 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.

Thank you @SEPURI-SAI-KRISHNA for this contribution, and especially for the candid PR description: the explicit note that this is hardening rather than a vulnerability, the mutation result you reported, and the honest statement about which tests can and cannot prove the timing property. That made the review much easier. I re-derived everything from the source at the PR head. There are no other reviews or comments on this PR so far, so there is nothing to +1 or contradict.

What Problem Does This PR Solve?

The Zeta REST/Web UI Basic auth filter compared the request credentials to the configured ones with String.equals joined by &&. String.equals exits at the first differing character, and && skips the password comparison entirely when the username is wrong. Response time can therefore (in theory) distinguish "wrong username" from "right username, wrong password" and grow with the number of correct leading characters (CWE-208).

Fix approach: evaluate both comparisons unconditionally into locals, and compare the UTF-8 bytes through MessageDigest.isEqual, with an explicit null guard for unset configuration.

Simple example: a request with admin:wrong against configured admin:s3cret previously did one full username comparison plus a short password comparison; a request with root:wrong did only a short username comparison and never touched the password. After this PR both do the same two comparisons.

1. Code Change Review

1.1 Core Logic Analysis

Runtime path (normal path IS reached by every authenticated request when basic auth is enabled):

Jetty request
  -> JettyService registers new BasicAuthFilter(httpConfig) (JettyService.java:194)
  -> BasicAuthFilter.doFilter
       enableBasicAuth false -> chain.doFilter (unchanged)
       header missing / not "Basic " -> 401 (unchanged)
       decode Base64, split(":", 2), length must be 2 (unchanged)
       usernameMatches = credentialMatches(username, configuredUser)
       passwordMatches = credentialMatches(password, configuredPassword)
       both true -> chain.doFilter, else 401 + WWW-Authenticate

Before: username.equals(cfgUser) && password.equals(cfgPass).
After: two locals computed up front, then usernameMatches && passwordMatches. The && is now applied to already computed booleans, so the second comparison is no longer skipped. The helper returns false for a null configured value and otherwise calls MessageDigest.isEqual(provided bytes, expected bytes).

Correctness: accept/reject semantics are identical for every case in the PR table. provided can never be null at the call sites because it comes from split(":", 2) with length 2. The null guard preserves the old String.equals(null) == false behavior, so an unset credential still yields 401 and not a 500. This is a precise, local change; I found no behavioral regression.

1.2 Compatibility Impact

Fully compatible. No option, default, public signature, serialization format or checkpoint state changes. Any credential that authenticated before still authenticates; anything rejected is still rejected.

1.3 Performance / Side-Effect Analysis

Negligible. One extra short byte comparison on the username-mismatch path and two small byte[] allocations per request per credential (getBytes). Basic auth requests are low volume, so there is no meaningful CPU/GC/lock impact. No new threads, locks, retries or logging. The filter lives in the Zeta engine server, so I reviewed it at engine grade: it is stateless, per-request, and does not touch checkpoint, scheduling or Hazelcast threads.

1.4 Error Handling and Logging

No blocking issues found. One non-blocking observation:

Issue 1: The "length of the configured credential is not revealed" claim depends on the JDK version

  • Location: BasicAuthFilter.java, credentialMatches javadoc and the PR description (argument-order reasoning).
  • Problem: The claim is verified against JDK 17 bytecode. SeaTunnel is built and shipped for Java 8 (the project targets Java 1.8). From my recollection of the JDK 8 implementation of MessageDigest.isEqual, it returns false immediately when the two array lengths differ, and only loops over the first array when lengths are equal. I could not execute code here, so this is an assumption to double check on your side with javap against a JDK 8 rt.jar. If it holds, on Java 8 the configured credential length can still be probed via a timing difference between equal and unequal lengths, and the javadoc comment would overstate the guarantee.
  • Potential risk: Only a documentation and expectation gap. The PR itself states this is hardening and the byte-by-byte accumulation still removes the leading-character dependency, which was the main discrepancy. No functional effect.
  • Best improvement: Either soften the javadoc ("on JDK 11+ the length is not revealed; on earlier JDKs only equal-length comparisons are constant time"), or, if you want length hiding on every JDK, compare fixed-length digests, for example MessageDigest.isEqual(sha256(provided), sha256(expected)). The second option is optional; I would not require it.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Good. New private helper has a clear javadoc explaining why (argument order, null contract), and the inline comment before the two locals explains why both comparisons are evaluated eagerly. No wildcard imports, @Slf4j unchanged, no System.out. License header is present on the new test file as far as I can see in the diff context.

2.2 Test Coverage and Test Stability

Coverage: BasicAuthFilterTest is new and covers success, wrong password, wrong username, prefix credential, all three unset-credential combinations (guards the NPE regression that this rewrite could introduce), and auth disabled. BasicAuthenticationIT gains a correct-username/wrong-password case and a prefix case, mirroring the existing negative test. As you correctly note, no black-box test can distinguish the old and new comparison; the tests guard the null-handling risk and the unchanged accept/reject contract, which is appropriate here. I agree with not adding a timing assertion.

Stability: Stable. The unit tests use Mockito mocks and a lambda chain with no sleeps, no static state, no ordering dependence and no timing assertions (BasicAuthFilterTest.java, whole file). The IT cases are independent single HTTP calls using the same fixture as existing cases.

CI note: the fork Build is red on three jobs (Windows unit-test, all-connectors-it-7, doris-connector-it). None of them execute code on the changed path in a way I could link to this change; the BasicAuthenticationIT is not in the failed list. I could not attribute the Windows unit-test failure to a specific test from the log excerpt I could retrieve, so I am not calling it a known flake. Please re-run the failed jobs and confirm the Windows job is green or shows a failure outside BasicAuthFilterTest.

2.3 Documentation Updates

No user-visible option or behavior changes, so no docs/en or docs/zh update is needed.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix. Minimal, localized to the single comparison site.

3.2 Maintainability

Good. The javadoc protects the argument order from a careless future swap. Having a unit test for this previously untested filter is a net gain.

3.3 Extensibility

Fine. The helper is private and trivially reusable if other credential checks appear in the REST layer.

3.4 Historical-Version Compatibility

No impact on old configs, saved jobs, checkpoints or savepoints; the HTTP contract (401 + WWW-Authenticate) is unchanged.

4. Issue Summary

Number Issue Location Severity
1 Length-hiding javadoc claim only holds on newer JDKs (Java 8 likely returns early on length mismatch) BasicAuthFilter.java credentialMatches javadoc Low

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers - must be fixed: none.
  2. Recommended fixes - non-blocking: Issue 1 (soften the javadoc claim, or hash both sides to a fixed length if length hiding on Java 8 is desired).

Overall assessment: a small, correct, behavior-preserving hardening with a thoughtful null guard and a sensible regression suite. The PR description is honest about what is and is not proven, which I appreciate.

Better alternative: none needed; the SHA-256-then-compare variant in Issue 1 is purely optional.

Existing maintainer approvals or change requests: none on this PR.

CI/sync status: the fork Build is red on Windows unit-test, all-connectors-it-7 and doris-connector-it, which I could not link to this change. Next step: re-run only the failed jobs (use the minimal rerun granularity) and confirm they pass or fail outside the touched classes. The branch is 14 commits behind dev with no reported conflicts; syncing is not required for this review.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Thanks for the review, @DanielLeens. You flagged Issue 1 as an assumption to check, so I checked it, and it does not hold: JDK 8 has the same time-constant implementation.

From openjdk/jdk8u, jdk/src/share/classes/java/security/MessageDigest.java:

int result = 0;
result |= lenA - lenB;

// time-constant comparison
for (int i = 0; i < lenA; i++) {
    // If i >= lenB, indexB is 0; otherwise, i.
    int indexB = ((i - lenB) >>> 31) * i;
    result |= digesta[i] ^ digestb[indexB];
}
return result == 0;

There is no early return on a length mismatch. The difference is folded into result and the loop still runs lenA times, with a branchless index so a shorter digestb is read at index 0 rather than skipped. That is the same shape I verified in the JDK 17 bytecode, so the javadoc claim holds on the Java 8 target and does not need softening.

Two honest caveats. The early returns that do exist are reference identity, either argument null, and lenB == 0, so an empty configured credential is distinguishable. That is a misconfiguration rather than a credential to protect, and it is the same on both JDKs. And I read current jdk8u; I cannot rule out that a very early 8u build predates the time-constant version, though the comment in the source suggests it was written that way deliberately.

On the SHA-256-then-compare variant: agreed it is optional, and I would rather not. It would hide the length on any implementation, but it also adds a digest per request and a dependency on the hash for something the comparison already gives us on both JDKs in question.

Happy to add a line to the javadoc recording that this was verified on 8u and 17 if you think it is worth pinning.

On the CI question, you asked whether the Windows unit-test is green or fails outside BasicAuthFilterTest. It is the latter, and I can be specific: BasicAuthFilterTest ran and passed 6 of 6 on that job before it died, and the job then failed on Could not resolve dependencies for project org.apache.seatunnel:seatunnel-flink-starter-common. An infrastructure failure, not a test. The same class passed 6 of 6 on all four unit-test legs, JDK 8 and 11 on both Linux and Windows. BasicAuthenticationIT also ran in engine-v2-it (8) and reported Tests run: 9, Failures: 0, Errors: 0, which is the seven existing cases plus the two added here. Rerunning the failed jobs now.

@SEZ9

SEZ9 commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator

Thanks @SEPURI-SAI-KRISHNA, that settles the JDK 8 question. The jdk8u source you pasted has the same shape as what you saw in the 17 bytecode: length difference folded into result, loop runs lenA times, branchless index for the shorter array. No early exit on length mismatch, so the javadoc claim stands as written on the Java 8 target.

Agreed on skipping the SHA-256-then-compare variant. A digest per request to hide the length of a credential that is already compared in constant time on both JDKs we ship against is not worth the extra moving part.

On the caveats:

  • The lenB == 0 early return is fine to leave as is. An empty configured username or password is a misconfiguration, not a secret, and the null guard already covers the unset case. I would not add a code path for it.
  • Yes, please add the one-line javadoc note that the constant-time property was verified against jdk8u and 17. It is cheap and it saves the next reader from re-deriving this.

On CI, thanks for the breakdown. BasicAuthFilterTest passing 6 of 6 on all four unit-test legs and BasicAuthenticationIT reporting 9 run / 0 failures in engine-v2-it (8) is what I wanted to see; the seatunnel-flink-starter-common dependency resolution failure on the Windows job is clearly infra. Ping me once the rerun finishes so I can confirm it is green across the board.

Remaining asks before merge:

  1. Javadoc line recording the 8u / 17 verification.
  2. Green rerun of the previously failed job.

Nothing else from my side.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Both done.

1. Javadoc note. Added to credentialMatches in BasicAuthFilter, immediately after the paragraph explaining why the request value is passed first:

Verified against the OpenJDK 8u source and the JDK 17 bytecode. Both fold the length difference into the accumulator and run the loop for the full length of the first argument, so neither returns early on a length mismatch.

That records the two things this thread established, so the next reader does not have to re-derive either.

2. Fresh run. Pushing the javadoc change gives a new head, so the whole check runs again rather than just the one job that hit the seatunnel-flink-starter-common dependency resolution failure. Will report back here once it finishes.

Nothing else changed in the diff.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Both done, and the full run has now finished.

1. Javadoc note. ad78cbc8e adds four lines to credentialMatches, all inside the existing comment block:

Verified against the OpenJDK 8u source and the JDK 17 bytecode. Both fold the length difference into the accumulator and run the loop for the full length of the first argument, so neither returns early on a length mismatch.

2. The rerun you asked about is green. Build 36849854713 on 8de4031fa, the commit carrying the actual fix, finished attempt 3 at 2026-10-03 17:43 UTC with conclusion: success: 81 jobs passed, 13 skipped, none failed. The three jobs @DanielLeens flagged all passed on that attempt:

job result
unit-test (8, windows-latest) success
all-connectors-it-7 (8, ubuntu-latest) success
doris-connector-it (8, ubuntu-latest) success

The javadoc push started a fresh full Build, 37184991698. It finished 79 success, 13 skipped, 1 failed, 1 cancelled. Neither is reachable from this diff:

On whether this diff could cause either: the commit on this head adds four lines and every one is inside a /** */ block, so the bytecode is unchanged. In the failing engine-v2-it (8) job BasicAuthenticationIT reported Tests run: 9, Failures: 0, Errors: 0.

Happy to rerun both jobs if you would rather see the aggregate green, though #12313 will keep recurring until it is fixed.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Build triage for be329bc45. The badge is red; none of it is this change.

Run 37757336877: 78 success, 2 failure, 1 cancelled, 13 skipped.

all-connectors-it-7 (8): one failure, in a connector this diff does not touch.

AmazondynamodbIT.testAmazondynamodb{TestContainer}[4]
  table sink_table is empty. ==> expected: <true> but was: <false>
  4 tests, 1 failure

37.0 minutes against a 150 minute limit, so not a timeout. I could not find an open issue naming this test, so I am reporting it as triage rather than calling it a known flake. It is one occurrence, which I do not think is enough to file on; happy to if you disagree.

all-connectors-it-2 (8): infrastructure, not a test. 22.2 minutes against the same 150 minute limit, and its test-report artifact contains no failing test reports at all, so the job died before or outside the tests rather than failing one.

paimon-connector-it (8) is a timeout, which GitHub records as cancelled: 180.7 minutes against timeout-minutes: 180.

What this change's own tests did. engine-v2-it passed on both legs, which is where BasicAuthenticationIT runs, so the two cases added there are green. For the record, from the earlier run at ad78cbc8e where that job was red for an unrelated reason, the IT itself was clean and both new cases ran by name:

BasicAuthenticationIT  Tests run: 9, Failures: 0, Errors: 0  133.583 s
  testAccessWithCorrectUsernameAndWrongPassword   14.696s
  testAccessWithPrefixOfCorrectCredentials        14.801s

That closes the caveat the description used to carry about those two cases never having been executed. The eight BasicAuthFilterTest unit cases pass locally and in unit-test.

So nothing here is attributable to the credential comparison change, which touches only BasicAuthFilter and its two test classes.

@DanielLeens DanielLeens 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.

Thanks @SEPURI-SAI-KRISHNA for the two follow-up commits, and for acting on the note from my previous review. I re-read the whole PR at the latest head be329bc459d7 from scratch (not just the incremental commits). There are no reviews or comments from other reviewers on this PR, so there is nothing to +1 or contradict. One thing needs a correction in this round: I previously raised the JDK 8 length-handling point from memory, and this time I checked it against real JDK 8 bytecode. The result contradicts the new javadoc paragraph, so please see Issue 1.

What Problem Does This PR Solve?

  • User pain point: the Zeta REST / Web UI Basic auth filter compared the request credentials with String.equals joined by &&. String.equals stops at the first differing character and && skips the password comparison when the username is wrong, so response time can in theory separate "wrong username" from "right username, wrong password" and grow with the number of correct leading characters (CWE-208).
  • Fix approach: evaluate both comparisons unconditionally into locals and compare UTF-8 bytes with MessageDigest.isEqual, with an explicit null guard for unset configuration.
  • One-sentence summary: make the Basic auth credential check do the same work whether the username, the password or neither is right.

Simple example: admin:wrong against configured admin:s3cret used to do a full username comparison plus a short password comparison, while root:wrong did only a short username comparison. After this PR both do the same two comparisons.

1. Code Change Review

1.1 Core Logic Analysis

Runtime path (every authenticated request hits it when enable-basic-auth is true):

Jetty request
  -> JettyService registers new BasicAuthFilter(httpConfig)      JettyService.java:194
  -> BasicAuthFilter.doFilter                                      BasicAuthFilter.java:59
       enable-basic-auth false           -> chain.doFilter (unchanged)            :63-66
       header missing / not "Basic "     -> 401 (unchanged)                       :75, :104-106
       Base64 decode, split(":", 2), length == 2                                  :78-83
       usernameMatches = credentialMatches(username, cfgUser)                     :92-93
       passwordMatches = credentialMatches(password, cfgPassword)                 :94-95
       both true -> chain.doFilter, else 401 + WWW-Authenticate                   :96-106

Before: username.equals(cfgUser) && password.equals(cfgPass).
After: two locals computed first, then usernameMatches && passwordMatches on plain booleans, so the second comparison is no longer skipped. credentialMatches (BasicAuthFilter.java:126-133) returns false for a null configured value, otherwise MessageDigest.isEqual(provided bytes, expected bytes).

Correctness: accept and reject semantics are identical to the old code for every case I traced. provided cannot be null at the call sites because it comes from split(":", 2) with length 2. The null guard preserves the old String.equals(null) == false behavior (401, not 500). The two commits since my last review only add a javadoc paragraph (:118-120) and more unit tests; production logic is unchanged since the first commit. This is a precise, local fix and I found no behavioral regression.

1.2 Compatibility Impact

Fully compatible. No option, default (admin / admin, ServerConfigOptions.java:374-384), public signature, serialization format or checkpoint state changes. Anything that authenticated before still authenticates; anything rejected is still rejected. No incompatible-changes.md entry is needed.

1.3 Performance / Side-Effect Analysis

Negligible. One extra short byte comparison on the username-mismatch path and two small byte[] allocations per credential per request. Basic auth traffic is low volume, so no meaningful CPU, GC, lock or network effect. The filter is stateless and per-request and does not touch checkpoint, scheduling or Hazelcast threads. No new threads, locks, retries or logging.

1.4 Error Handling and Logging

No functional blockers. The one formal issue is about an inaccurate claim in the new javadoc:

Issue 1: The new javadoc says JDK 8u does not return early on a length mismatch, but the JDK 8 builds I inspected do

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/filter/BasicAuthFilter.java:113-120 (the "Verified against the OpenJDK 8u source and the JDK 17 bytecode ... neither returns early on a length mismatch" paragraph, plus the "length of the configured credential is not revealed" sentence just above it).
  • Problem description: credentialMatches calls MessageDigest.isEqual(provided, expected) on every authenticated request, so this javadoc is the contract readers will trust for the timing property. I disassembled java.security.MessageDigest.isEqual with javap -c from two JDK 8 installs (1.8.0_171 and 1.8.0_71). In both, right after the null checks there is aload_0; arraylength; aload_1; arraylength; if_icmpeq ...; iconst_0; ireturn, which means it returns false immediately when the two lengths differ, before any XOR loop. The JDK 11.0.9 and later builds I checked have the newer shape that folds the length difference into the accumulator, which matches what the paragraph describes for JDK 17. I only had 8u171 and 8u71 available, so a later 8u update may differ, and I could not check the openjdk:8u342 image that CI uses. Because SeaTunnel ships for Java 8, the statement "neither returns early" is not safe as written.
  • Potential risk: no change to accept/reject behavior, and the main hardening goal (no dependence on how many leading characters match) still holds on every JDK. The risk is documentation only: on those Java 8 builds an attacker can still learn whether a guess has the same byte length as the configured credential, while the javadoc says the length is not revealed. A false security claim in code tends to be trusted later and to stop people from reconsidering it.
  • Best improvement:
    • Option A (recommended, one small edit): reword the paragraph to what is verified, for example "On JDK 11.0.9+ and 17 the comparison does not return early on a length mismatch; on the JDK 8 builds checked (8u71, 8u171) isEqual returns early when lengths differ, so only the equality of the lengths can be inferred, not the leading bytes." Please also check the exact 8u update you target before keeping any 8u claim.
    • Option B (optional): compare fixed-length digests, MessageDigest.isEqual(sha256(provided), sha256(expected)), which hides the length on every JDK at the price of two SHA-256 computations per request, still negligible here.
  • Severity: Medium (documentation correctness for a security property)
  • Raised by another reviewer: No (it is a follow-up to the Low note in my earlier review, now backed by bytecode evidence)

2. Code Quality Assessment

2.1 Coding Standards

Good. The private helper has a javadoc that explains why (argument order, null contract), the inline comment before the two locals explains why both comparisons are eager, and the new test file has the ASF header. No wildcard imports, no System.out, @Slf4j unchanged.

2.2 Test Coverage and Test Stability

BasicAuthFilterTest (new, BasicAuthFilterTest.java) covers: success (:48), wrong password (:59), wrong username (:70), prefix credential (:81), all three unset-credential combinations (:94, guards the NPE a byte-based rewrite could introduce), auth disabled (:111), and in the latest commit the empty-credential matrix (:124) and multi-byte UTF-8 near misses (:161). BasicAuthenticationIT gains a correct-username/wrong-password case and a prefix case. As the PR description says, no black-box test can distinguish old from new timing behavior, so these tests guard the null handling and the unchanged accept/reject contract, which is the right scope. The multi-byte test is a good addition because the comparison moved from String to bytes. I agree with not adding a timing assertion.

Small non-blocking observation (Low): testEmptyConfiguredCredentialMatchesOnlyAnEmptyProvidedValue (:124) deliberately pins that a deployment configured with an empty username and password accepts an empty pair. That is unchanged from String.equals and the comment explains it, so I am fine with it; just be aware the test will need a deliberate update if the project ever rejects empty credentials at config load time.

Stability rating: Stable. The unit tests use Mockito mocks and a lambda chain, with no sleeps, no static state, no ordering dependence and no timing assertions. The IT cases are independent single HTTP calls against the same fixture as the existing negative test.

2.3 Documentation Updates

No user-visible option or behavior change, so no docs/en or docs/zh update is needed. The only documentation concern is the javadoc in Issue 1.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix, localized to the single comparison site.

3.2 Maintainability

Good. The comments protect the argument order and the eager evaluation from a careless future simplification, and the previously untested filter now has a unit test.

3.3 Extensibility

Fine. The helper is private and trivially reusable if other credential checks appear in the REST layer.

3.4 Historical-Version Compatibility

No impact on old configs, saved jobs, checkpoints or savepoints. The HTTP contract (401 plus WWW-Authenticate) is unchanged.

4. Issue Summary

Number Issue Location Severity
1 Javadoc claims JDK 8u does not return early on a length mismatch; the 8u71 and 8u171 bytecode does BasicAuthFilter.java:113-120 Medium

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers - must be fixed:
    • Issue 1 (Medium): correct the javadoc so it does not assert a property that the Java 8 builds I checked do not have. It is a comment-only edit (Option A), no logic change.
  2. Recommended fixes - non-blocking:
    • Optional Option B for Issue 1 if you want length hiding on every JDK.
    • The empty-credential note in 2.2 needs no action now.

Overall assessment: a small, correct, behavior-preserving hardening with a thoughtful null guard and a sensible regression suite. The only thing standing in the way is one inaccurate sentence in a security-related comment. Existing maintainer approvals or change requests: none on this PR.

CI and sync status at head be329bc459d7: the apache-side Build check points to the fork run https://github.com/SEPURI-SAI-KRISHNA/seatunnel/actions/runs/37757336877, which is completed with failures in all-connectors-it-2 (8), all-connectors-it-7 (8) and paimon-connector-it (8) (cancelled). I read the failed logs: all-connectors-it-2 stopped on a Maven Central Connection reset while resolving mysql-connector-java:8.0.16 for connector-cdc-mongodb-e2e (network), and all-connectors-it-7 failed in AmazondynamodbIT.testAmazondynamodb (table sink_table is empty, AmazondynamodbIT.java:100). Neither touches the Basic auth path, and all four unit-test jobs (JDK 8 and 11, ubuntu and windows) are green, so I read these as unrelated to this PR (this is an inference from the logs). The failing set also differs from the previous head, which points the same way. Next step after the javadoc fix: the branch is 80 commits behind dev with no conflict (GitHub reports it as blocked only by the review requirement), so please sync with the latest dev, which will rerun CI, or rerun only the failed jobs; if either fails again outside the touched classes, paste the link here and I will help narrow it down.

Thanks again for the careful work and for being so open about what the tests can and cannot prove. Happy to re-review as soon as you push the javadoc update!

@github-actions github-actions Bot removed the reviewed label Oct 10, 2026
@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Thanks @DanielLeens, and thank you for disassembling it rather than letting my sentence stand. You are right, and the way I was wrong is worse than the sentence: there is no JDK 8 on this machine, so "Verified against the OpenJDK 8u source" was never something I could have checked. I wrote a security claim I had no means to test.

Taking Option A. The javadoc now states only what was measured, and names the build each claim came from:

  • javap -c here on 11.0.32, 17.0.20 and 21.0.12: the length difference is folded into the accumulator (isub then ior) and the loop bound is the first argument's length (istore_2, then if_icmpge), with no early return on differing lengths. That also confirms the argument-order reasoning.
  • For 8u71 and 8u171 it attributes the if_icmpeq plus immediate return false to your disassembly rather than claiming it as mine, and says byte-length equality can still be inferred there while the leading bytes cannot.
  • It names no boundary update. My first attempt at this correction said "hidden only from 11.0.9 onwards", repeating the same mistake in miniature: 11.0.9 came from your review, not from anything I ran, and the build I disassembled is 11.0.32. It now says only that the listed builds were disassembled and that which 8u or 11.x update first changed shape was not established.

One thing I found while checking, on every build I disassembled: a second early exit for an empty configured value. isEqual tests the second argument's length first (iload_3, ifne) and returns whether the provided value is empty too, without entering the loop. It only arises from an empty configured credential, which the empty-credential test already pins, so it is recorded in the javadoc rather than acted on.

On Option B I would rather not, and that is yours to overrule. Digesting both sides hides the length on every JDK, but it adds a hash to an authenticated path for a property ASF Security already concluded is not a vulnerability here, and the digest's own runtime is input-length dependent, so it narrows the signal rather than removing it. Say so and I will push it.

Comment-only: git diff has no non-comment line. BasicAuthFilterTest 8 tests 0F 0E, spotless clean.

Agreed on the CI read, and thanks for pinning all-connectors-it-2 to the Maven Central Connection reset. That matches the artifact side, where that job had no failing test reports at all. Syncing with dev for a fresh run.

@DanielLeens DanielLeens 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.

Thanks @SEPURI-SAI-KRISHNA for taking Option A so quickly, and for the honest note that the earlier "verified against 8u" sentence could not be checked on your machine. I re-read the whole PR at the latest head 30728339cfd5 (not just the new commit). My only blocker from the previous round (Issue 1, the javadoc claim about JDK 8) is now resolved, and CI was never my blocker, so I am changing my conclusion to approve. There are no other reviews on this PR; @SEZ9's earlier comment thread (javadoc note, rerun) is already addressed.

What Problem Does This PR Solve?

  • User pain point: BasicAuthFilter compared request credentials with String.equals joined by &&, so response time could separate "wrong username" from "right username, wrong password" and grow with the number of matching leading characters (CWE-208).
  • Fix approach: compute both comparisons into locals first, then compare UTF-8 bytes with MessageDigest.isEqual, with an explicit null guard for unset configuration.
  • One-sentence summary: the Basic auth check now does the same work whichever half of the credential is wrong.

1. Code Change Review

1.1 Core Logic Analysis

Runtime path (hit by every request when enable-basic-auth is true): JettyService registers new BasicAuthFilter(httpConfig) -> BasicAuthFilter.doFilter -> Base64 decode, split(":", 2), length 2 -> credentialMatches(username, cfgUser) and credentialMatches(password, cfgPassword) evaluated eagerly -> both true goes to chain.doFilter, otherwise 401 plus WWW-Authenticate.

What changed since my last review (be329bc459d7 -> 30728339cfd5): one commit, a comment-only edit to the credentialMatches javadoc (BasicAuthFilter.java:110-135). git diff shows no non-comment line touched, so the production logic is byte-for-byte the same as the version I already traced. Accept and reject semantics match the old String.equals behavior; provided is never null at the call sites, and an unset configured value still gives 401 rather than a 500.

1.2 Compatibility Impact

Fully compatible. No option, default (admin / admin), public signature, serialization format or checkpoint state changes. Anything that authenticated before still authenticates.

1.3 Performance / Side-Effect Analysis

Negligible: one extra short byte comparison on the username-mismatch path and two small byte[] allocations per request. The filter is stateless and per-request, and does not touch checkpoint, scheduling or Hazelcast threads.

1.4 Error Handling and Logging

No blocking issues found. The javadoc now states what was measured (11.0.32, 17.0.20 and 21.0.12 fold the length difference into the accumulator; the 8u71 and 8u171 bytecode I disassembled returns early on a length mismatch) and explicitly tells readers not to rely on length hiding on Java 8. That matches the javap -c disassembly I did for my previous review, so Issue 1 from my last review is resolved. The extra note about the early exit for an empty configured value is also consistent with what I saw, and the empty-credential test already pins it.

Issue 1 (Low, optional): the javadoc refers to "A reviewer disassembled 8u71 and 8u171"

  • Location: BasicAuthFilter.java:121-122
  • Problem description: a comment in source should read as a standalone fact; "a reviewer" has no meaning for someone reading the file in two years, and the attribution lives better in the PR history.
  • Best improvement: rephrase to "On the Java 8 builds checked (8u71, 8u171), isEqual returns false as soon as the array lengths differ ...". Wording only, no behavior change.
  • Severity: Low (non-blocking)
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Good. The helper's javadoc explains why (argument order, null contract, eager evaluation), no wildcard imports, no System.out, ASF header present on the new test file.

2.2 Test Coverage and Test Stability

Unchanged in this commit and still appropriate: BasicAuthFilterTest (success, wrong password, wrong username, prefix credential, three unset-credential combinations, auth disabled, empty-credential matrix, multi-byte UTF-8 near misses) guards the null handling and the unchanged accept/reject contract, and BasicAuthenticationIT gains the correct-username/wrong-password and prefix cases. As the description says, no black-box test can tell old from new timing, so I agree with not adding a timing assertion. Stability rating: Stable (Mockito mocks, no sleeps, no static state, no timing assertions).

2.3 Documentation Updates

No user-visible change, so no docs/en or docs/zh update is needed.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix at the single comparison site.

3.2 Maintainability

Good; the comments protect the argument order and the eager evaluation from a careless future simplification, and the previously untested filter now has a unit test.

3.3 Extensibility

Fine; the helper is private and easy to reuse if other credential checks appear in the REST layer.

3.4 Historical-Version Compatibility

No impact on old configs, saved jobs, checkpoints or savepoints. The HTTP contract is unchanged.

4. Issue Summary

Number Issue Location Severity
1 Javadoc says "A reviewer disassembled ..."; state it as a fact instead BasicAuthFilter.java:121-122 Low

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers - must be fixed: none.
  2. Recommended fixes - non-blocking: Issue 1 (wording only; fine to fold into any later push).

Overall assessment: a small, correct, behavior-preserving hardening with an honest javadoc. Better alternative: none needed (the SHA-256-then-compare variant stays optional, and I agree with skipping it). Existing maintainer approvals or change requests: none.

CI and sync status at head 30728339cfd5: the apache-side Build points to the fork run https://github.com/SEPURI-SAI-KRISHNA/seatunnel/actions/runs/38112411913 (77 success, 13 skipped, 4 failed). The jobs relevant to this change are green: all four unit-test legs (JDK 8 and 11, ubuntu and windows) and both engine-v2-it legs (where BasicAuthenticationIT runs). The 4 failures, from the logs I read (my inference, not a known-flake claim):

  • engine-k8s-it (8) and (11): the "install k8s" step failed at the k3s download (a curl SSL error, then "Download failed"), so no test ran.
  • transform-v2-it-part-1 (8): a single failure, TestFilterRowKindIT.testFilterRowKindMultiTable[1] (TestFilterRowKindIT.java:53, expected: <0> but was: <1>, on the Flink container), in a transform this diff does not touch.
  • paimon-connector-it (8): all 4 failures are in PaimonWithS3IT (300s timeouts each), a connector this diff does not touch.

None of these touch BasicAuthFilter. The branch is 91 commits behind dev with no conflict (the BLOCKED merge state is just the pending review requirement), so syncing with the latest dev or re-running only the failed jobs is the cheapest next step; if the same jobs fail again outside the touched classes, paste the link here and I will help narrow it down.

Thanks again for the careful work, and for being so open about what the tests can and cannot prove!

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Thanks @DanielLeens, and thanks for re-reading the whole PR rather than just the new commit.

Issue 1 taken. You are right that a source comment should stand on its own: "a reviewer" means nothing to someone opening the file in two years, and the attribution belongs in this thread rather than in the code. It now reads as fact, naming the builds and the bytecode on each side without saying who ran what.

While in there I re-audited the rest of that Javadoc against what I had actually run and tightened two more of my own sentences that still claimed too much: "present in every build checked" became "seen in all three builds disassembled here", since the 8u builds were yours and were never checked for that case; and "reads exactly as many bytes as its first argument holds" is now scoped to when it enters the loop, because on the 8u shape a length mismatch reads none at all.

Comment-only again: git diff has no non-comment line. BasicAuthFilterTest 8 tests 0F 0E, spotless clean.

On your CI note, one of the four has a firmer answer than a flake. You flagged these as inference rather than known-flake claims, so to close that out:

Synced with the latest dev in the push above, so fea1ac0a4 is now in the branch. BasicAuthFilterTest is still 8 of 8 on the merged tree and spotless is clean; the merge is a pure one, with my head differing from dev in only the three files this PR owns.

@DanielLeens DanielLeens 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.

Thanks again @SEPURI-SAI-KRISHNA for the quick follow-up and for the careful re-audit of your own javadoc. I re-read the whole PR at the latest head 364514f12cdb from scratch, not just the new commits. There are no reviews from other reviewers beyond the earlier comment thread with @SEZ9 (already resolved), so there is nothing to +1 or contradict.

What Problem Does This PR Solve?

  • User pain point: BasicAuthFilter compared request credentials with String.equals joined by &&, so response time could separate "wrong username" from "right username, wrong password" and grow with the number of matching leading characters.
  • Fix approach: compute both comparisons into locals first, then compare UTF-8 bytes with MessageDigest.isEqual, with an explicit null guard for unset configuration.
  • One-sentence summary: the Basic auth check now does the same work whichever half of the credential is wrong.

1. Code Change Review

1.1 Core Logic Analysis

Runtime path (hit by every request when enable-basic-auth is true):

Jetty request
  -> JettyService registers new BasicAuthFilter(httpConfig)
  -> BasicAuthFilter.doFilter
       auth disabled / header missing / not "Basic " / bad split -> unchanged behavior
       usernameMatches = credentialMatches(username, cfgUser)
       passwordMatches = credentialMatches(password, cfgPassword)
       both true -> chain.doFilter, else 401 + WWW-Authenticate

What changed since my last review (30728339cfd5 -> 364514f12cdb): two commits. b3f26aeb9e0 is a javadoc-only edit of credentialMatches; the second is a merge of the latest dev. Against the dev merge base the PR still touches only three files (BasicAuthFilter, BasicAuthFilterTest, BasicAuthenticationIT), so the merge brought in nothing unrelated. The production logic is unchanged from the version I already traced: accept and reject semantics match the old String.equals behavior, provided is never null at the call sites, and an unset configured value still gives 401 rather than a 500.

1.2 Compatibility Impact

Fully compatible. No option, default, public signature, serialization format or checkpoint state changes.

1.3 Performance / Side-Effect Analysis

Negligible: one extra short byte comparison on the username-mismatch path and two small byte[] allocations per request. The filter is stateless and does not touch checkpoint, scheduling or Hazelcast threads.

1.4 Error Handling and Logging

No issues. My only item from the last round (Issue 1, Low: the javadoc said "A reviewer disassembled ...") is resolved: the javadoc now states the measured facts per build (11.0.32, 17.0.20, 21.0.12 fold the length difference into the accumulator; 8u71 and 8u171 return early on a length mismatch), says not to rely on length hiding on Java 8, and scopes the empty-configured-value early exit to the three builds actually disassembled. The "reads exactly as many bytes as its first argument holds" sentence is now correctly conditioned on entering the loop. This is consistent with the bytecode I looked at earlier. I could not independently re-disassemble the 11.0.32 and 21.0.12 builds, but nothing in the comment overclaims relative to what the code does.

2. Code Quality Assessment

2.1 Coding Standards

Good. The helper's javadoc explains why (argument order, null contract, eager evaluation); no wildcard imports, no System.out, ASF header present on the new test file.

2.2 Test Coverage and Test Stability

Unchanged in these commits and still appropriate: BasicAuthFilterTest (success, wrong password, wrong username, prefix credential, unset-credential combinations, auth disabled, empty-credential matrix, multi-byte UTF-8 near misses) fails if the accept/reject contract or null handling regresses, and BasicAuthenticationIT adds the correct-username/wrong-password and prefix cases. No black-box test can tell old from new timing, so not adding a timing assertion is the right call. Stability rating: Stable (Mockito mocks, no sleeps, no static state).

2.3 Documentation Updates

No user-visible change, so no docs/en or docs/zh update is needed.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix at the single comparison site.

3.2 Maintainability

Good; the comments protect the argument order and eager evaluation from a careless future simplification.

3.3 Extensibility

Fine; the helper is private and easy to reuse.

3.4 Historical-Version Compatibility

No impact on old configs, saved jobs, checkpoints or savepoints. The HTTP contract is unchanged.

4. Issue Summary

Number Issue Location Severity
- No open issues (previous Low javadoc wording issue is resolved) - -

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers - must be fixed: none.
  2. Recommended fixes - non-blocking: none.

Overall assessment: a small, correct, behavior-preserving change with an honest, build-scoped javadoc. Better alternative: none needed. Existing maintainer approvals or change requests: none outstanding.

CI at head 364514f12cdb: the apache-side Build points to the fork run https://github.com/SEPURI-SAI-KRISHNA/seatunnel/actions/runs/38150594554 (78 success, 13 skipped, 3 failed). All unit-test legs I checked and both engine-v2-it legs (where BasicAuthenticationIT runs) are green. The 3 failures are in connectors this diff does not touch: all-connectors-it-6 (11) (DatabendCDCSinkIT.testDatabendSinkCDC condition timeout) and all-connectors-it-2 (11) / (17) (CassandraIT.testCassandra and testCassandraMultiTableSource, expected: <0> but was: <1>). This is my inference from the logs, not a known-flake claim. The branch is just synced with dev, so re-running only the failed jobs is the cheapest next step; if the same jobs fail again, paste the link here and I will help narrow it down.

Thanks again for the careful work!

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Thanks @DanielLeens. Nothing outstanding on my side either, and I appreciate the note that the javadoc does not overclaim; after rewriting it twice that was the one thing I was unsure of.

One prediction from my last comment came good, so closing it out. I said the TestFilterRowKindIT failure was #12116, fixed by #12216, and that the sync would clear it rather than reroll it. At the merged head all four transform-v2-it jobs are green, so that one is resolved rather than lucky.

On the three failures, I narrowed the Cassandra one rather than leave it to you. Both land on the first assertion of their test:

CassandraIT.java:134   Assertions.assertEquals(0, execResult.getExitCode());   testCassandra
CassandraIT.java:144   Assertions.assertEquals(0, execResult.getExitCode());   testCassandraMultiTableSource

So expected: <0> but was: <1> is the job exit code, not a row count: the job never ran successfully on that container, and the test failed before touching Cassandra.

The invocation pattern is the useful part. From the failsafe report, of the nine invocations only [2] fails:

testCassandraMultiTableSource{TestContainer}[1] pass  [2] FAIL  [3] pass  [4] pass
testCassandra{TestContainer}[1]                 pass  [2] FAIL  [3] pass  [4] pass

and [2] fails identically on both the JDK 11 and the JDK 17 leg, taking 31.7 to 35.7 seconds across the four failing invocations rather than hitting a timeout. Two independent runners failing the same engine invocation the same way is not a race; it reads as that one engine not being able to run this job on current dev. I did not identify which engine [2] maps to, so I am not guessing at it.

Correcting myself on tracking before you spend time on it: no issue I can find names CassandraIT, so that one is not a known flake. DatabendCDCSinkIT is named, in #12482, among the signatures it lists as known flaky or shared, though #12482 is a CI matrix proposal rather than a bug report for it. I had drafted "neither is tracked" before reading #12482's body properly.

Not attributable to this PR either way: the diff is BasicAuthFilter plus its two tests, enable-basic-auth defaults to false, and the Cassandra e2e module submits jobs through the container CLI rather than the REST filter.

Also worth noting the matrix moved while this branch was behind: the connector E2E legs now run JDK 11 and 17, where earlier runs here were 8 and 11.

@SEZ9

SEZ9 commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator

Thanks @SEPURI-SAI-KRISHNA, this is a thorough write-up and I agree with the reading.

On the earlier Issue 1: your check that JDK 8 carries the same time-constant MessageDigest.isEqual implementation settles that point, so it is closed from my side. Nothing else is open on BasicAuthFilter or its two tests.

On the CI analysis:

  • TestFilterRowKindIT: agreed, with the #12116 / #12216 link and all four transform-v2-it jobs green after the dev sync, that one is resolved rather than lucky.
  • CassandraIT: your narrowing is convincing. Both failures sitting on the first assertEquals(0, execResult.getExitCode()) means the job itself exited 1 before the test touched Cassandra, and the same [2] invocation failing identically on the JDK 11 and JDK 17 legs in ~32-36s is not a race pattern. I also agree it cannot be attributed to this PR: the diff is the filter plus tests, enable-basic-auth defaults to false, and the Cassandra e2e path submits via the container CLI, not the REST filter.
  • DatabendCDCSinkIT: fine to treat as the known signature listed in #12482, with the caveat you noted that #12482 is a matrix proposal rather than a bug report.

Two small asks so this does not get lost once the PR is merged:

  1. If the failsafe report or the parameterized test display name lets you map invocation [2] to a concrete engine, please add that to your comment. If it is not recoverable from the artifacts, say so and I will not hold on it.
  2. Since no existing issue names CassandraIT, please open one with the exit-code detail and the [2]-only pattern you pasted here, and link it back on this thread. That gives the dev failure its own home instead of living in this PR's history.

Nothing further needed on the code itself.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @SEPURI-SAI-KRISHNA for the thorough write-up, and thanks @SEZ9 for the follow-ups. I have nothing further on the code: BasicAuthFilter and its two tests are unchanged since my last pass, and the time-constant comparison point is settled.

On the CassandraIT failure, I can add one data point to help with the tracking item. On the current dev head b0f6feddf9 (run 38340962420, job all-connectors-it-2 (11, ubuntu-latest)), the very same two assertions fail: CassandraIT.testCassandra:134 and CassandraIT.testCassandraMultiTableSource:144, both expected: <0> but was: <1>. The run's own summary names the failing invocation as TestContainer[4], and the log of that job shows the Flink 1.20.1 taskmanager container together with a Direct buffer memory error. So the job exit code is non-zero because the engine run fails in that container, which matches your conclusion that it is not related to this PR. (Invocation numbering may differ between your report and mine, so please treat [2] vs [4] as a labeling detail rather than a contradiction; I did not map it further than the container named in the log.) I also noticed #12732, which targets a Cassandra E2E flake, but its description talks about a row-count race after TRUNCATE, which is a different assertion from the exit-code one here, so I would not expect it to fix this lane; I have not verified that further.

Since dev itself is red on this lane, a rerun will not clear it. The minimal next step is simply to wait for an upstream fix, then sync the latest dev and rerun only the failed jobs. If you open the tracking issue SEZ9 suggested, the [N]-only pattern plus the Direct buffer memory line from the Flink 1.20.1 taskmanager would be the most useful details to include.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

Thanks @SEZ9 and @DanielLeens.

One correction first, because it is the security-relevant half. @SEZ9, you wrote that my check settled that JDK 8 carries the same time-constant isEqual. It is the other way round: there is no JDK 8 on this machine, so I never checked it. I disassembled 11.0.32, 17.0.20 and 21.0.12, where the length difference is folded into the accumulator. @DanielLeens disassembled 8u71 and 8u171 and found the opposite, an if_icmpeq on the two lengths then an immediate return false. My original javadoc claimed 8u was verified and was wrong. The leading-byte property holds on every shape; only the length stays inferable on 8u, which is what the javadoc now says.

Ask 1, mapping the invocation. Recoverable, but not from the artifacts, which carry only {TestContainer}[2]. The job log has it: the invocation provider names each container as it starts, in a fixed order repeated per test method.

[1] Flink:1.18.0 pass   [2] Flink:1.20.1 FAIL   [3] SeaTunnel:dev pass   [4] Spark:3.3.0 pass

So [2] is Flink 1.20.1, matching the container you named on dev as [4], and both Direct buffer memory lines fall inside its windows. The part I missed until I checked the order: Flink 1.18.0 passes in the same job, so this is specific to the 1.20.1 image rather than to Flink.

That gave a root cause rather than a signature:

io.netty EncoderException: OutOfMemoryError: Direct buffer memory
  -> ConnectionInitException: STARTUP step 1, failed to send request
  -> AllNodesFailedException: All 1 node(s) tried for query failed  (20x)
  -> job exits 1 -> the exit-code assertion fails

The driver cannot allocate a direct buffer for its first CQL frame in that taskmanager, so no row is read. A direct-memory budget problem in the container, not a Cassandra race.

Ask 2, the tracking issue. Filed as #12757, with the container mapping, the exception chain and both reproductions, including dev head b0f6feddf on run 38340962420 which I confirmed is red on dev itself.

It raises one point for a maintainer: #12732 quotes the same message as a TRUNCATE race, yet on dev the only assertions able to print expected: <0> are those two exit-code ones, and its patch adds no count assertion. Set out in the issue to be reconciled, not as a claim they are wrong, since I have not read their job log.

Agreed with @DanielLeens that a rerun cannot clear this while dev is red.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @SEPURI-SAI-KRISHNA, the Flink 1.20.1 mapping and the root-cause chain are very helpful, and thanks for correcting the JDK 8 point in the javadoc.

One concrete next step that should clear the red Build: the direct-memory failure you traced in #12757 now has a fix on dev. #12756 ([Fix][E2E] Prevent direct memory exhaustion in Flink 1.20 Cassandra tests, merge commit 07d6f2235a) was merged at 2026-10-13 16:03 UTC. It only touches Flink20Container.java in seatunnel-e2e-common, so it does not interact with this PR's diff. Your head 364514f12c (committed 2026-10-11) does not contain it yet.

So my earlier "a rerun cannot clear this while dev is red" no longer holds. Please merge the latest dev into this branch (this one time it is useful, not just because the branch is behind) and let Build run again. The CassandraIT failures on the Flink 1.20.1 container should then go away. If all-connectors-it-6 (DatabendCDCSinkIT) is still red afterwards, that one is independent of this change and a single --failed rerun is the right tool.

I have nothing further on the code. This is a static review comment; I did not execute the PR.

@SEZ9

SEZ9 commented Oct 14, 2026

Copy link
Copy Markdown
Collaborator

@SEPURI-SAI-KRISHNA thanks, and you are right on the correction: I misattributed the JDK 8 check to you. Your disassembly covered 11.0.32, 17.0.20 and 21.0.12 (length folded into the accumulator); the 8u71/8u171 finding (if_icmpeq on the lengths, then return false) came from the other review, not from you. The javadoc wording you describe is the accurate one: leading-byte property holds on every shape, only the length stays inferable on 8u. One small ask so I can close this out: please confirm that wording is what is in the pushed head 364514f12c, or push it if it is still local.

On the invocation mapping, that fully answers my question. [2] = Flink 1.20.1, Flink 1.18.0 passing in the same job, and the Direct buffer memory -> ConnectionInitException -> AllNodesFailedException -> exit 1 chain is a much better artifact than the {TestContainer}[2] signature alone. Thanks for filing #12757 with both reproductions including dev head b0f6feddf on run 38340962420, and for flagging the #12732 overlap for reconciliation rather than asserting it; that is the right way to leave it.

Since #12756 (07d6f2235a) landed on dev and only touches Flink20Container.java in seatunnel-e2e-common, the remaining steps are:

  1. Merge latest dev into this branch so the Flink 1.20 direct-memory fix is picked up.
  2. Let Build run again; the CassandraIT failures on the Flink 1.20.1 container should disappear.
  3. If all-connectors-it-6 (DatabendCDCSinkIT) is still red afterwards, that one is independent and a single failed-jobs rerun is enough.

Nothing else outstanding from me on the code; once the javadoc confirmation and a green run after the dev sync are in, I am ready to approve.

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

@SEZ9 @DanielLeens confirmed, and thank you both.

1. The javadoc wording is in the pushed head, not local. It went up in b3f26aeb9 ("[Fix][Zeta] State the MessageDigest.isEqual javadoc as fact and scope it to the builds checked", 2026-10-11 15:06:57 UTC), which is the commit before the dev merge that produced the current head 364514f12c. The file is seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/rest/filter/BasicAuthFilter.java, javadoc on credentialMatches. The two sentences you asked about read:

On the builds disassembled with javap -c, 11.0.32, 17.0.20 and 21.0.12, the length difference is folded into the accumulator and the loop runs for the first argument's length, with no early return when the lengths differ. On the Java 8 builds checked, 8u71 and 8u171, isEqual instead compares the two array lengths with if_icmpeq and returns false immediately when they differ, so there the equality of the byte lengths can still be inferred, though the leading bytes cannot.

It names no boundary update on purpose, and the 8u sentence is impersonal because that measurement is not mine.

2. Syncing dev. 07d6f2235a is on dev and my head predates it, so I will merge and let Build run again.

3. Credit where it belongs. #12756 was opened by @JeremyXin at 2026-10-13 12:47 UTC, 47 minutes before I filed #12757 at 13:34 UTC, with the same EncoderException / Direct buffer memory / AllNodesFailedException chain. The fix was already in flight; my issue did not prompt it. @nzw921rx closed #12757 as fixed by it this morning.

4. The #12732 overlap resolved itself. NganWave closed #12732 unmerged at 2026-10-14 04:38 UTC with no comment, so the TRUNCATE-race reading was neither confirmed nor refuted in public. What landed is the task off-heap memory change, not a TRUNCATE wait. I have nothing further owed there.

Expected after the sync: all-connectors-it-2 green, and all-connectors-it-6 (DatabendCDCSinkIT) possibly still red, which is independent of this diff and needs only a failed-jobs rerun.

@DanielLeens DanielLeens 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.

Thanks @SEPURI-SAI-KRISHNA for syncing dev as suggested, and for the clear confirmation that the corrected javadoc wording is in the pushed history (b3f26aeb9e); thanks @SEZ9 for the follow-up as well. The new head db7c965c1c is only a merge of the latest dev. I re-read the full diff against current dev and compared this PR's own patch at my previously reviewed head 364514f12c with this head: the two are identical, so the production code, tests and javadoc are exactly what I reviewed last round. The javadoc confirmation I asked for is satisfied (credentialMatches in BasicAuthFilter.java carries the per-build, scoped wording), and the branch now contains #12756, the Flink 1.20 direct-memory fix. I have no blocker, so I am approving. This review is intentionally concise because the content is unchanged.

What Problem Does This PR Solve?

  • User pain point: BasicAuthFilter compared request credentials with String.equals joined by &&, so response time could separate "wrong username" from "right username, wrong password" and grow with the number of matching leading characters (CWE-208).
  • Fix approach: evaluate both comparisons into locals first, then compare UTF-8 bytes with MessageDigest.isEqual, with an explicit null guard for an unset configured credential.
  • One-sentence summary: the Basic auth check now does the same work whichever half of the credential is wrong.

1. Code Change Review

1.1 Core Logic Analysis

Jetty request (enable-basic-auth = true)
  -> BasicAuthFilter.doFilter
       header missing / not "Basic " / bad split -> unchanged behavior (401)
       usernameMatches = credentialMatches(username, cfgUser)
       passwordMatches = credentialMatches(password, cfgPassword)
       both true -> chain.doFilter, else 401 + WWW-Authenticate

Re-checked at this head: both locals are computed before the branch (no && short-circuit), the request value is passed as the first argument to MessageDigest.isEqual, and an unset configured value returns false (401) rather than throwing. Accept/reject semantics match the old String.equals behavior.

1.2 Compatibility Impact

Fully compatible. No option, default, public signature, serialization format or checkpoint state changes; the HTTP contract is unchanged.

1.3 Performance / Side-Effect Analysis

Negligible: one extra short byte comparison on the username-mismatch path and two small byte[] allocations per request. Stateless filter, no impact on checkpoint, scheduling or Hazelcast threads.

1.4 Error Handling and Logging

No issues. The javadoc states measured facts per JDK build and does not overclaim length hiding on Java 8.

2. Code Quality Assessment

2.1 Coding Standards

Good: the helper's javadoc and the inline comment explain why (eager evaluation, argument order, null contract); no wildcard imports, no System.out.

2.2 Test Coverage and Test Stability

BasicAuthFilterTest (success, wrong password, wrong username, prefix credential, unset-credential combinations, auth disabled, empty-credential matrix, multi-byte UTF-8 near misses) and BasicAuthenticationIT would fail if the accept/reject contract or null handling regressed. No black-box test can tell old from new timing, so omitting a timing assertion is the right call. Stability rating: Stable (Mockito mocks, no sleeps, no static state).

CI: the apache-side Build check is currently in progress on this head. On the previous head the only reds were CassandraIT (Flink 1.20 direct memory, fixed by #12756, now in this branch) and DatabendCDCSinkIT, both outside the files this PR touches. If all-connectors-it-6 (DatabendCDCSinkIT) is still red after this run, a single failed-jobs rerun is the right tool; if anything else fails, please paste the link and I will help narrow it down.

2.3 Documentation Updates

No user-visible change, so no docs/en or docs/zh update is needed.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix at the single comparison site.

3.2 Maintainability

Good; the comments protect the argument order and eager evaluation from a careless future simplification.

3.3 Extensibility

Fine; the helper is private and easy to reuse.

3.4 Historical-Version Compatibility

No impact on old configs, saved jobs, checkpoints or savepoints.

4. Issue Summary

Number Issue Location Severity
- No open issues - -

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers - must be fixed: none.
  2. Recommended fixes - non-blocking: none.

Overall assessment: a small, correct, behavior-preserving change with an honest, build-scoped javadoc. Better alternative: none needed. The remaining gates are the in-progress CI run and a maintainer approval (the PR shows review-required).

Thanks again for the careful work!

@SEPURI-SAI-KRISHNA

Copy link
Copy Markdown
Collaborator Author

@SEZ9 @DanielLeens the green run you both asked for is in.

Build on head db7c965c1c is passing: run 38523018557, 94 jobs, finished 2026-10-15 03:18 UTC. Daniel, thank you for re-verifying that this head is only a dev merge over 364514f12c and that the patch itself is unchanged.

It took one failed-jobs rerun, and both reds were outside this PR's files:

  1. all-connectors-it-6 (11): DatabendCDCSinkIT.testDatabendSinkCDC{TestContainer}[1], in connector-databend-e2e. This is the signature named in [Improve][CI] Run connector E2E on one host JDK in PRs; keep both JDKs in the nightly (sub-task of #11513) #12482.
  2. google-pubsub-connector-it (17): GooglePubSubIT.testGooglePubSubSourceAcknowledgesAfterCheckpoint, java.util.concurrent.TimeoutException at GooglePubSubIT.java:228, in connector-google-pubsub-e2e.

Both passed on the rerun with no code change, which is what you would expect of a container timing flake rather than a real regression. This PR touches only seatunnel-engine-server and seatunnel-engine-e2e, so neither connector module is reachable from its diff.

The CassandraIT failures that were red on the previous head are gone, as predicted once #12756 (07d6f2235a) came in with the dev sync.

So the state is: javadoc confirmation given and verified in the pushed history at b3f26aeb9, dev synced, CI green, and no review comments outstanding. The only remaining gate is a committer approval, since the PR still shows review-required.

@SEZ9

SEZ9 commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator

@SEPURI-SAI-KRISHNA thanks for closing the loop on the CI question — that was the one open item from my side, and it is answered.

To confirm what I take from your update:

  • Build on head db7c965c1c is passing (run 38523018557), and that head is only a dev merge over 364514f12c with the PR's own patch unchanged.
  • The two reds on the first attempt (DatabendCDCSinkIT.testDatabendSinkCDC in connector-databend-e2e, and GooglePubSubIT.testGooglePubSubSourceAcknowledgesAfterCheckpoint in connector-google-pubsub-e2e) both passed on the failed-jobs rerun with no code change. Since this PR only touches seatunnel-engine-server and seatunnel-engine-e2e, I agree neither module is reachable from the diff, so I treat those as unrelated flakes rather than something this PR needs to act on.
  • The earlier CassandraIT failures are gone now that 07d6f2235a is in the branch via the dev sync.
  • The corrected javadoc wording for credentialMatches is in the pushed history at b3f26aeb9, which is what I asked for last round.

So from my perspective: the javadoc ask is satisfied, dev is synced, CI is green, and I have nothing further outstanding on the previously raised point. As you note, the PR still shows review-required, so the remaining gate is a committer approval; nothing more is needed from you for that.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks @SEPURI-SAI-KRISHNA. I independently confirm the current head db7c965c1ce295ae8c326264818d9b18a952121d has a successful Apache Build and that the PR patch is unchanged since the reviewed head. CI was the last open item from my review, so I have no remaining source-side concern. A write-access maintainer can take the final approval/merge.

@davidzollo davidzollo 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.

Approving. The constant-time basic-auth credential comparison is a precise, low-risk hardening, the earlier review points are addressed, and the Build check is green on this exact head. Thanks @SEPURI-SAI-KRISHNA. Enqueueing for merge.

@davidzollo
davidzollo added this pull request to the merge queue Oct 18, 2026
Merged via the queue into apache:dev with commit 0600214 Oct 18, 2026
4 checks passed
Asthenia0412 added a commit to Asthenia0412/seatunnel that referenced this pull request Oct 18, 2026
…cy (apache#12595)

Signed-off-by: Asthenia0412 <Asthenia0412@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Improve][Zeta] BasicAuthFilter compares credentials with String.equals and a short-circuit

4 participants