diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm index 9a54c84545..4434e72321 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.mm @@ -740,7 +740,11 @@ static FlutterAutofillType autofillTypeOf(NSDictionary* configuration) { @"Expected a FlutterTextRange for range (got %@).", [range class]); NSRange textRange = ((FlutterTextRange*)range).range; NSAssert(textRange.location != NSNotFound, @"Expected a valid text range."); - return [self.text substringWithRange:textRange]; + // Sanitize the range to prevent going out of bounds. + int location = MIN(textRange.location, self.text.length); + int length = MIN(self.text.length - location, textRange.length); + NSRange safeRange = NSMakeRange(location, length); + return [self.text substringWithRange:safeRange]; } // Replace the text within the specified range with the given text, diff --git a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.m b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.m index 4b0a0d4ce9..4e7a3b6108 100644 --- a/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.m +++ b/engine/src/flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPluginTest.m @@ -211,6 +211,24 @@ FLUTTER_ASSERT_ARC XCTAssertEqual(range.length, 2); } +- (void)testTextInRange { + NSDictionary* config = self.mutableTemplateCopy; + [config setValue:@{@"name" : @"TextInputType.url"} forKey:@"inputType"]; + [self setClientId:123 configuration:config]; + NSArray* inputFields = self.installedInputViews; + FlutterTextInputView* inputView = inputFields[0]; + + [inputView insertText:@"test"]; + + UITextRange* range = [FlutterTextRange rangeWithNSRange:NSMakeRange(0, 20)]; + NSString* substring = [inputView textInRange:range]; + XCTAssertEqual(substring.length, 4); + + range = [FlutterTextRange rangeWithNSRange:NSMakeRange(10, 20)]; + substring = [inputView textInRange:range]; + XCTAssertEqual(substring.length, 0); +} + - (void)testNoZombies { // Regression test for https://github.com/flutter/flutter/issues/62501. FlutterSecureTextInputView* passwordView = [[FlutterSecureTextInputView alloc] init];