This is an automated email from the ASF dual-hosted git repository. garydgregory pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-lang.git
commit f7558bcf43f4c0468b29d05a4818079bff9a3eb8 Author: Gary Gregory <[email protected]> AuthorDate: Sun Nov 15 15:24:15 2026 -0500 Fix overflow in StringUtils Levenshtein distance calculations Use zero-based outer loops in both overloads to handle CharSequence inputs of Integer.MAX_VALUE length. Take the minimum before adding the edit cost to prevent overflow in the unbounded overload. Add exhaustive small-input comparisons and opt-in maximum-length regressions using virtual inputs. Update Javadoc and release notes. Assisted-By: OpenAI Codex --- src/changes/changes.xml | 1 + .../java/org/apache/commons/lang3/StringUtils.java | 23 +-- .../lang3/StringUtilsLevenshteinDistanceTest.java | 180 +++++++++++++++++++++ 3 files changed, 193 insertions(+), 11 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index e9c346188..32a4d7139 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -93,6 +93,7 @@ The <action> type attribute can be add,update,fix,remove. <action type="fix" dev="ggregory" due-to="Gary Gregory, simpleqt">Fix integer overflow in StringUtils.join range handling.</action> <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity overflow in StringUtils.wrapIfMissing(String, String) when only one wrapper is missing and the result is representable.</action> <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent premature length overflow in StringUtils.repeat(String, String, int) when the final result is representable but the intermediate result with a trailing separator is not.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent loop-counter and edit-cost overflow in StringUtils.getLevenshteinDistance for CharSequence inputs of Integer.MAX_VALUE length, with and without a threshold.</action> <!-- ADD --> <!-- UPDATE --> </release> diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 0bce0a157..3cddd2773 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -2334,7 +2334,7 @@ public static double getJaroWinklerDistance(final CharSequence first, final Char * </p> * * <p> - * The implementation uses a single-dimensional array of length s.length() + 1. See + * The implementation uses a single-dimensional array whose length is one greater than that of the shorter input. See * <a href="https://blog.softwx.net/2014/12/optimizing-levenshtein-algorithm-in-c.html"> * https://blog.softwx.net/2014/12/optimizing-levenshtein-algorithm-in-c.html</a> for details. * </p> @@ -2401,16 +2401,16 @@ public static int getLevenshteinDistance(CharSequence s, CharSequence t) { p[i] = i; } - for (j = 1; j <= m; j++) { + for (j = 0; j < m; j++) { upperleft = p[0]; - jOfT = t.charAt(j - 1); - p[0] = j; + jOfT = t.charAt(j); + p[0] = j + 1; for (i = 1; i <= n; i++) { upper = p[i]; cost = s.charAt(i - 1) == jOfT ? 0 : 1; - // minimum of cell to the left+1, to the top+1, diagonally left and up +cost - p[i] = Math.min(Math.min(p[i - 1] + 1, p[i] + 1), upperleft + cost); + // Take the minimum before adding one: the left cell can be Integer.MAX_VALUE on the final row. + p[i] = Math.min(Math.min(p[i - 1], p[i]) + 1, upperleft + cost); upperleft = upper; } } @@ -2546,13 +2546,14 @@ distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only Arrays.fill(d, Integer.MAX_VALUE); // iterates through t - for (int j = 1; j <= m; j++) { - final char jOfT = t.charAt(j - 1); // jth character of t - d[0] = j; + for (int j = 0; j < m; j++) { + final char jOfT = t.charAt(j); // jth character of t + final int row = j + 1; + d[0] = row; // compute stripe indices, constrain to array size - final int min = Math.max(1, j - threshold); - final int max = j > Integer.MAX_VALUE - threshold ? n : Math.min(n, j + threshold); + final int min = Math.max(1, row - threshold); + final int max = row > Integer.MAX_VALUE - threshold ? n : Math.min(n, row + threshold); // the stripe may lead off of the table if s and t are of different sizes if (min > max) { diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsLevenshteinDistanceTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsLevenshteinDistanceTest.java new file mode 100644 index 000000000..21cfd7d81 --- /dev/null +++ b/src/test/java/org/apache/commons/lang3/StringUtilsLevenshteinDistanceTest.java @@ -0,0 +1,180 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.lang3; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Boundary and exhaustive small-input tests for the legacy Levenshtein implementations. + * + * <p> + * Enable the maximum-length scans with {@code -Dtest.stringutils.large.levenshtein=true}. + * These tests use constant-size virtual inputs but perform billions of iterations; no large heap is needed. + * </p> + */ +class StringUtilsLevenshteinDistanceTest extends AbstractLangTest { + + private static final class RepeatedCharSequence implements CharSequence { + + private final int length; + + private RepeatedCharSequence(final int length) { + this.length = length; + } + + @Override + public char charAt(final int index) { + if (index < 0 || index >= length) { + throw new IndexOutOfBoundsException("Index: " + index + ", length: " + length); + } + return 'a'; + } + + @Override + public int length() { + return length; + } + + @Override + public CharSequence subSequence(final int start, final int end) { + if (start < 0 || end < start || end > length) { + throw new IndexOutOfBoundsException(); + } + return new RepeatedCharSequence(end - start); + } + + @Override + public String toString() { + return StringUtils.repeat('a', length); + } + } + + // Invoke the legacy methods reflectively without introducing deprecated API usages. + private static int distance(final CharSequence left, final CharSequence right) throws ReflectiveOperationException { + final Method method = StringUtils.class.getMethod("getLevenshteinDistance", CharSequence.class, CharSequence.class); + return (Integer) method.invoke(null, left, right); + } + + private static int distance(final CharSequence left, final CharSequence right, final int threshold) throws ReflectiveOperationException { + final Method method = StringUtils.class.getMethod("getLevenshteinDistance", CharSequence.class, CharSequence.class, int.class); + return (Integer) method.invoke(null, left, right, threshold); + } + + /** + * Uses a full matrix as an independent oracle for the optimized row and stripe implementations. + */ + private static int referenceDistance(final String left, final String right) { + final int[][] costs = new int[left.length() + 1][right.length() + 1]; + for (int i = 0; i <= left.length(); i++) { + costs[i][0] = i; + } + for (int j = 0; j <= right.length(); j++) { + costs[0][j] = j; + } + for (int i = 1; i <= left.length(); i++) { + for (int j = 1; j <= right.length(); j++) { + final int substitution = costs[i - 1][j - 1] + (left.charAt(i - 1) == right.charAt(j - 1) ? 0 : 1); + costs[i][j] = Math.min(substitution, Math.min(costs[i - 1][j] + 1, costs[i][j - 1] + 1)); + } + } + return costs[left.length()][right.length()]; + } + + @Test + void testAllShortBinaryInputs() throws ReflectiveOperationException { + final List<String> inputs = new ArrayList<>(); + for (int length = 1; length <= 4; length++) { + for (int bits = 0; bits < (1 << length); bits++) { + final StringBuilder text = new StringBuilder(length); + for (int bit = 0; bit < length; bit++) { + text.append((bits & (1 << bit)) == 0 ? 'x' : 'y'); + } + inputs.add(text.toString()); + } + } + for (final String left : inputs) { + for (final String right : inputs) { + final int expected = referenceDistance(left, right); + final String context = left + " -> " + right; + assertEquals(expected, distance(left, right), context); + for (final int threshold : new int[] { 0, 1, 2, 3, 4, 5, Integer.MAX_VALUE - 1, Integer.MAX_VALUE }) { + assertEquals(expected <= threshold ? expected : -1, distance(left, right, threshold), context + ", threshold=" + threshold); + } + } + } + } + + @ParameterizedTest + @ValueSource(ints = { Integer.MAX_VALUE - 1, Integer.MAX_VALUE }) + void testMaximumLengthEmptyAndRejectedInputs(final int length) throws ReflectiveOperationException { + final CharSequence input = new RepeatedCharSequence(length); + assertEquals(length, distance("", input)); + assertEquals(length, distance(input, "")); + assertEquals(length, distance("", input, length)); + assertEquals(length, distance(input, "", length)); + assertEquals(-1, distance("", input, length - 1)); + assertEquals(-1, distance(input, "", length - 1)); + assertEquals(-1, distance("a", input, length - 2)); + assertEquals(-1, distance(input, "a", length - 2)); + } + + @ParameterizedTest + @CsvSource({ + "2147483646, a, false, 2147483645", + "2147483646, b, true, 2147483646", + "2147483647, a, false, 2147483646", + "2147483647, a, true, 2147483646", + "2147483647, b, false, 2147483647", + "2147483647, b, true, 2147483647", + "2147483647, aa, true, 2147483645" + }) + @EnabledIfSystemProperty(named = "test.stringutils.large.levenshtein", matches = "true") + void testMaximumLengthUnbounded(final int length, final String text, final boolean reverse, final int expected) + throws ReflectiveOperationException { + final CharSequence input = new RepeatedCharSequence(length); + assertEquals(expected, reverse ? distance(input, text) : distance(text, input)); + } + + @ParameterizedTest + @CsvSource({ + "2147483646, a, 2147483645, false, 2147483645", + "2147483646, b, 2147483645, true, -1", + "2147483647, a, 2147483646, false, 2147483646", + "2147483647, a, 2147483647, true, 2147483646", + "2147483647, b, 2147483646, false, -1", + "2147483647, b, 2147483647, true, 2147483647", + "2147483647, aa, 2147483645, false, 2147483645", + "2147483647, bb, 2147483645, true, -1" + }) + @EnabledIfSystemProperty(named = "test.stringutils.large.levenshtein", matches = "true") + void testMaximumLengthWithThreshold(final int length, final String text, final int threshold, final boolean reverse, final int expected) + throws ReflectiveOperationException { + final CharSequence input = new RepeatedCharSequence(length); + assertEquals(expected, reverse ? distance(input, text, threshold) : distance(text, input, threshold)); + } +}
