From fde7b1e5454ed169719562234799941d9e409135 Mon Sep 17 00:00:00 2001 From: i321222 Date: Thu, 12 Sep 2019 19:01:02 +0200 Subject: [PATCH] Avoid ArrayIndexOutOfBoundsException in SpEL's Indexer When index == arrayLength, the array index is also out of bounds. For this scenario, a SpelEvaluationException should be thrown instead of ArrayIndexOutOfBoundsException. Closes gh-23658 --- .../expression/spel/ast/Indexer.java | 2 +- .../expression/spel/ast/IndexerTests.java | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 spring-expression/src/test/java/org/springframework/expression/spel/ast/IndexerTests.java diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java index 6bcca868786..4ef4a0ed4ec 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java @@ -439,7 +439,7 @@ public class Indexer extends SpelNodeImpl { } private void checkAccess(int arrayLength, int index) throws SpelEvaluationException { - if (index > arrayLength) { + if (index >= arrayLength) { throw new SpelEvaluationException(getStartPosition(), SpelMessage.ARRAY_INDEX_OUT_OF_BOUNDS, arrayLength, index); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ast/IndexerTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ast/IndexerTests.java new file mode 100644 index 00000000000..ccae50f2c6e --- /dev/null +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ast/IndexerTests.java @@ -0,0 +1,23 @@ +package org.springframework.expression.spel.ast; + +import org.junit.jupiter.api.Test; +import org.springframework.expression.EvaluationException; +import org.springframework.expression.spel.standard.SpelExpression; +import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.expression.spel.support.SimpleEvaluationContext; +import org.springframework.expression.spel.testresources.Inventor; + +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +/** + * @author Joyce Zhan + */ +public class IndexerTests { + @Test + public void testAccess() { + SimpleEvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build(); + SpelExpression expression = (SpelExpression) new SpelExpressionParser().parseExpression("stringArrayOfThreeItems[3]"); + assertThatExceptionOfType(EvaluationException.class).isThrownBy(() -> + expression.getValue(context, new Inventor())); + } +} \ No newline at end of file