Fix crash in blink::AXSelection when selection is on shadow root

Bug: 998551
Change-Id: Ic8356adc9fa24752812bbaeca2aeb97aa4e2a4f6
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1791142
Commit-Queue: Jessica Tallon <jtallon@igalia.com>
Reviewed-by: Nektarios Paisios <nektar@chromium.org>
Cr-Commit-Position: refs/heads/master@{#695642}
diff --git a/third_party/blink/renderer/modules/accessibility/ax_selection.cc b/third_party/blink/renderer/modules/accessibility/ax_selection.cc
index 7532b8c..b7166cb 100644
--- a/third_party/blink/renderer/modules/accessibility/ax_selection.cc
+++ b/third_party/blink/renderer/modules/accessibility/ax_selection.cc
@@ -214,6 +214,9 @@
   const auto ax_extent =
       AXPosition::FromPosition(dom_extent, extent_affinity, extent_adjustment);
 
+  if (!ax_base.IsValid() || !ax_extent.IsValid())
+    return {};
+
   AXSelection::Builder selection_builder;
   selection_builder.SetBase(ax_base).SetExtent(ax_extent);
   return selection_builder.Build();
diff --git a/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc b/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc
index 4a10b2c..0f27d24 100644
--- a/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc
+++ b/third_party/blink/renderer/modules/accessibility/ax_selection_test.cc
@@ -1615,6 +1615,33 @@
       builder.SetBase(ax_position).SetExtent(ax_position).Build();
 }
 
+TEST_F(AccessibilitySelectionTest, InvalidSelectionOnAShadowRoot) {
+  GetPage().GetSettings().SetScriptEnabled(true);
+  SetBodyInnerHTML(R"HTML(
+		<div id="container">
+		</div>	
+	)HTML");
+  Element* const script_element =
+      GetDocument().CreateRawElement(html_names::kScriptTag);
+  script_element->setTextContent(R"SCRIPT(
+      var container = document.getElementById("container");
+			var shadow = container.attachShadow({mode: 'open'});
+			var button = document.createElement("button");
+			button.id = "button";
+			shadow.appendChild(button);
+      )SCRIPT");
+  GetDocument().body()->AppendChild(script_element);
+  UpdateAllLifecyclePhasesForTest();
+
+  Node* shadow_root = GetElementById("container")->GetShadowRoot();
+  const Position base = Position::EditingPositionOf(shadow_root, 0);
+  const Position extent = Position::EditingPositionOf(shadow_root, 1);
+
+  const auto selection =
+      SelectionInDOMTree::Builder().SetBaseAndExtent(base, extent).Build();
+  EXPECT_FALSE(AXSelection::FromSelection(selection).IsValid());
+}
+
 //
 // Declarative tests.
 //