Skip to content

Commit

Permalink
Fix CharArraysTests.testConstantTimeEquals() (#47346)
Browse files Browse the repository at this point in the history
The change #47238 fixed a first issue (#47076) but introduced 
another one that can be reproduced using:

org.elasticsearch.common.CharArraysTests > testConstantTimeEquals FAILED

java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at __randomizedtesting.SeedInfo.seed([DFCA64FE2C786BE3:ED987E883715C63B]:0)
at java.lang.String.substring(String.java:1963)
at org.elasticsearch.common.CharArraysTests.testConstantTimeEquals(CharArraysTests.java:74)

REPRODUCE WITH: ./gradlew ':libs:elasticsearch-core:test' --tests 
"org.elasticsearch.common.CharArraysTests.testConstantTimeEquals" 
-Dtests.seed=DFCA64FE2C786BE3 -Dtests.security.manager=true -Dtests.locale=fr-CA 
-Dtests.timezone=Pacific/Johnston -Dcompiler.java=12 -Druntime.java=8

that happens when the first randomized string has a length of 0.
  • Loading branch information
tlrx authored Oct 1, 2019
1 parent 6cfc2f4 commit 519fd9b
Showing 1 changed file with 8 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@

import java.nio.charset.StandardCharsets;

import static org.hamcrest.Matchers.is;

public class CharArraysTests extends ESTestCase {

public void testCharsToBytes() {
Expand Down Expand Up @@ -70,10 +72,12 @@ public void testConstantTimeEquals() {
assertTrue(CharArrays.constantTimeEquals(value.toCharArray(), value.toCharArray()));

// we want a different string, so ensure the first character is different, but the same overall length
final String other = new String(
randomAlphaOfLengthNotBeginningWith(value.substring(0, 1), value.length(), value.length()));
assertFalse("value: " + value + ", other: " + other, CharArrays.constantTimeEquals(value, other));
assertFalse(CharArrays.constantTimeEquals(value.toCharArray(), other.toCharArray()));
final int length = value.length();
final String other = length > 0 ? new String(randomAlphaOfLengthNotBeginningWith(value.substring(0, 1), length, length)) : "";
final boolean expectedEquals = length == 0;

assertThat("value: " + value + ", other: " + other, CharArrays.constantTimeEquals(value, other), is(expectedEquals));
assertThat(CharArrays.constantTimeEquals(value.toCharArray(), other.toCharArray()), is(expectedEquals));
}

private char[] randomAlphaOfLengthNotBeginningWith(String undesiredPrefix, int min, int max) {
Expand Down

0 comments on commit 519fd9b

Please sign in to comment.