Skip to content

Commit

Permalink
Fix XContentTypeTests where version was a negative byte (#63382)
Browse files Browse the repository at this point in the history
a random byte could be -128 and when used with Math.abs it would result
in an int 128. That in turn when casting back to byte would overflow and
result in -128 again.
Fixed with a randomNonNegativeByte method

closes #63342
  • Loading branch information
pgomulka authored Oct 8, 2020
1 parent 36f8346 commit 9b056e1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public void testFromRubbish() throws Exception {
}

public void testVersionedMediaType() {
String version = String.valueOf(Math.abs(randomByte()));
String version = String.valueOf(randomNonNegativeByte());
assertThat(XContentType.fromMediaType("application/vnd.elasticsearch+json;compatible-with=" + version),
equalTo(XContentType.JSON));
assertThat(XContentType.fromMediaType("application/vnd.elasticsearch+cbor;compatible-with=" + version),
Expand All @@ -119,7 +119,7 @@ public void testVersionedMediaType() {
}

public void testVersionParsing() {
byte version = (byte) Math.abs(randomByte());
byte version = randomNonNegativeByte();
assertThat(XContentType.parseVersion("application/vnd.elasticsearch+json;compatible-with=" + version),
equalTo(version));
assertThat(XContentType.parseVersion("application/vnd.elasticsearch+cbor;compatible-with=" + version),
Expand All @@ -146,12 +146,12 @@ public void testUnrecognizedParameter() {
is(nullValue())); }

public void testMediaTypeWithoutESSubtype() {
String version = String.valueOf(Math.abs(randomByte()));
String version = String.valueOf(randomNonNegativeByte());
assertThat(XContentType.fromMediaType("application/json;compatible-with=" + version), nullValue());
}

public void testAnchoring() {
String version = String.valueOf(Math.abs(randomByte()));
String version = String.valueOf(randomNonNegativeByte());
assertThat(XContentType.fromMediaType("sth_application/json;compatible-with=" + version + ".0"), nullValue());
assertThat(XContentType.fromMediaType("sth_application/json;compatible-with=" + version + "_sth"), nullValue());
assertThat(XContentType.fromMediaType("application/json;compatible-with=" + version + "_sth"), nullValue());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,11 @@ public static byte randomByte() {
return (byte) random().nextInt();
}

public static byte randomNonNegativeByte() {
byte randomByte = randomByte();
return (byte) (randomByte == Byte.MIN_VALUE ? 0 : Math.abs(randomByte));
}

/**
* Helper method to create a byte array of a given length populated with random byte values
*
Expand Down

0 comments on commit 9b056e1

Please sign in to comment.