Session.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. /*
  2. * Copyright (c) 2022, Florent Castelli <florent.castelli@gmail.com>
  3. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
  5. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  6. * Copyright (c) 2022, Tim Flynn <trflynn89@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include "Session.h"
  11. #include "BrowserConnection.h"
  12. #include "Client.h"
  13. #include <AK/Base64.h>
  14. #include <AK/NumericLimits.h>
  15. #include <AK/Time.h>
  16. #include <AK/URL.h>
  17. #include <LibCore/LocalServer.h>
  18. #include <LibCore/Stream.h>
  19. #include <LibCore/System.h>
  20. #include <LibGfx/PNGWriter.h>
  21. #include <LibGfx/Point.h>
  22. #include <LibGfx/Rect.h>
  23. #include <LibGfx/Size.h>
  24. #include <LibWeb/Cookie/Cookie.h>
  25. #include <LibWeb/Cookie/ParsedCookie.h>
  26. #include <LibWeb/WebDriver/ExecuteScript.h>
  27. #include <unistd.h>
  28. namespace WebDriver {
  29. Session::Session(unsigned session_id, NonnullRefPtr<Client> client)
  30. : m_client(move(client))
  31. , m_id(session_id)
  32. {
  33. }
  34. Session::~Session()
  35. {
  36. if (m_started) {
  37. auto error = stop();
  38. if (error.is_error()) {
  39. warnln("Failed to stop session {}: {}", m_id, error.error());
  40. }
  41. }
  42. }
  43. ErrorOr<Session::Window*, Web::WebDriver::Error> Session::current_window()
  44. {
  45. auto window = m_windows.get(m_current_window_handle);
  46. if (!window.has_value())
  47. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "Window not found");
  48. return window.release_value();
  49. }
  50. ErrorOr<void, Web::WebDriver::Error> Session::check_for_open_top_level_browsing_context_or_return_error()
  51. {
  52. (void)TRY(current_window());
  53. return {};
  54. }
  55. ErrorOr<NonnullRefPtr<Core::LocalServer>> Session::create_server(String const& socket_path, ServerType type, NonnullRefPtr<ServerPromise> promise)
  56. {
  57. dbgln("Listening for WebDriver connection on {}", socket_path);
  58. auto server = TRY(Core::LocalServer::try_create());
  59. server->listen(socket_path);
  60. server->on_accept = [this, type, promise](auto client_socket) mutable {
  61. switch (type) {
  62. case ServerType::Browser: {
  63. auto maybe_connection = adopt_nonnull_ref_or_enomem(new (nothrow) BrowserConnection(move(client_socket), m_client, session_id()));
  64. if (maybe_connection.is_error()) {
  65. promise->resolve(maybe_connection.release_error());
  66. return;
  67. }
  68. dbgln("WebDriver is connected to Browser socket");
  69. m_browser_connection = maybe_connection.release_value();
  70. break;
  71. }
  72. case ServerType::WebContent: {
  73. auto maybe_connection = adopt_nonnull_ref_or_enomem(new (nothrow) WebContentConnection(move(client_socket), m_client, session_id()));
  74. if (maybe_connection.is_error()) {
  75. promise->resolve(maybe_connection.release_error());
  76. return;
  77. }
  78. dbgln("WebDriver is connected to WebContent socket");
  79. m_web_content_connection = maybe_connection.release_value();
  80. break;
  81. }
  82. }
  83. if (m_browser_connection && m_web_content_connection)
  84. promise->resolve({});
  85. };
  86. server->on_accept_error = [promise](auto error) mutable {
  87. promise->resolve(move(error));
  88. };
  89. return server;
  90. }
  91. ErrorOr<void> Session::start()
  92. {
  93. auto promise = TRY(ServerPromise::try_create());
  94. auto browser_socket_path = String::formatted("/tmp/webdriver/browser_{}_{}", getpid(), m_id);
  95. auto browser_server = TRY(create_server(browser_socket_path, ServerType::Browser, promise));
  96. auto web_content_socket_path = String::formatted("/tmp/webdriver/content_{}_{}", getpid(), m_id);
  97. auto web_content_server = TRY(create_server(web_content_socket_path, ServerType::WebContent, promise));
  98. char const* argv[] = {
  99. "/bin/Browser",
  100. "--webdriver-browser-path",
  101. browser_socket_path.characters(),
  102. "--webdriver-content-path",
  103. web_content_socket_path.characters(),
  104. nullptr,
  105. };
  106. TRY(Core::System::posix_spawn("/bin/Browser"sv, nullptr, nullptr, const_cast<char**>(argv), environ));
  107. // FIXME: Allow this to be more asynchronous. For now, this at least allows us to propagate
  108. // errors received while accepting the Browser and WebContent sockets.
  109. TRY(promise->await());
  110. m_started = true;
  111. m_windows.set("main", make<Session::Window>("main", true));
  112. m_current_window_handle = "main";
  113. return {};
  114. }
  115. // https://w3c.github.io/webdriver/#dfn-close-the-session
  116. Web::WebDriver::Response Session::stop()
  117. {
  118. // 1. Perform the following substeps based on the remote end’s type:
  119. // NOTE: We perform the "Remote end is an endpoint node" steps in the WebContent process.
  120. m_web_content_connection->close_session();
  121. m_web_content_connection = nullptr;
  122. // 2. Remove the current session from active sessions.
  123. // NOTE: Handled by WebDriver::Client.
  124. // 3. Perform any implementation-specific cleanup steps.
  125. m_browser_connection->async_quit();
  126. m_started = false;
  127. // 4. If an error has occurred in any of the steps above, return the error, otherwise return success with data null.
  128. return JsonValue {};
  129. }
  130. // 9.1 Get Timeouts, https://w3c.github.io/webdriver/#dfn-get-timeouts
  131. JsonObject Session::get_timeouts()
  132. {
  133. // 1. Let timeouts be the timeouts object for session’s timeouts configuration
  134. auto timeouts = timeouts_object(m_timeouts_configuration);
  135. // 2. Return success with data timeouts.
  136. return timeouts;
  137. }
  138. // 9.2 Set Timeouts, https://w3c.github.io/webdriver/#dfn-set-timeouts
  139. Web::WebDriver::Response Session::set_timeouts(JsonValue const& payload)
  140. {
  141. // 1. Let timeouts be the result of trying to JSON deserialize as a timeouts configuration the request’s parameters.
  142. auto timeouts = TRY(json_deserialize_as_a_timeouts_configuration(payload));
  143. // 2. Make the session timeouts the new timeouts.
  144. m_timeouts_configuration = move(timeouts);
  145. // 3. Return success with data null.
  146. return JsonValue {};
  147. }
  148. // 10.3 Back, https://w3c.github.io/webdriver/#dfn-back
  149. Web::WebDriver::Response Session::back()
  150. {
  151. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  152. TRY(check_for_open_top_level_browsing_context_or_return_error());
  153. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  154. // 3. Traverse the history by a delta –1 for the current browsing context.
  155. m_browser_connection->async_back();
  156. // FIXME: 4. If the previous step completed results in a pageHide event firing, wait until pageShow event
  157. // fires or for the session page load timeout milliseconds to pass, whichever occurs sooner.
  158. // FIXME: 5. If the previous step completed by the session page load timeout being reached, and user
  159. // prompts have been handled, return error with error code timeout.
  160. // 6. Return success with data null.
  161. return JsonValue();
  162. }
  163. // 10.4 Forward, https://w3c.github.io/webdriver/#dfn-forward
  164. Web::WebDriver::Response Session::forward()
  165. {
  166. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  167. TRY(check_for_open_top_level_browsing_context_or_return_error());
  168. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  169. // 3. Traverse the history by a delta 1 for the current browsing context.
  170. m_browser_connection->async_forward();
  171. // FIXME: 4. If the previous step completed results in a pageHide event firing, wait until pageShow event
  172. // fires or for the session page load timeout milliseconds to pass, whichever occurs sooner.
  173. // FIXME: 5. If the previous step completed by the session page load timeout being reached, and user
  174. // prompts have been handled, return error with error code timeout.
  175. // 6. Return success with data null.
  176. return JsonValue();
  177. }
  178. // 10.5 Refresh, https://w3c.github.io/webdriver/#dfn-refresh
  179. Web::WebDriver::Response Session::refresh()
  180. {
  181. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  182. TRY(check_for_open_top_level_browsing_context_or_return_error());
  183. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  184. // 3. Initiate an overridden reload of the current top-level browsing context’s active document.
  185. m_browser_connection->async_refresh();
  186. // FIXME: 4. If url is special except for file:
  187. // FIXME: 1. Try to wait for navigation to complete.
  188. // FIXME: 2. Try to run the post-navigation checks.
  189. // FIXME: 5. Set the current browsing context with current top-level browsing context.
  190. // 6. Return success with data null.
  191. return JsonValue();
  192. }
  193. // 10.6 Get Title, https://w3c.github.io/webdriver/#dfn-get-title
  194. Web::WebDriver::Response Session::get_title()
  195. {
  196. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  197. TRY(check_for_open_top_level_browsing_context_or_return_error());
  198. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  199. // 3. Let title be the initial value of the title IDL attribute of the current top-level browsing context's active document.
  200. // 4. Return success with data title.
  201. return JsonValue(m_browser_connection->get_title());
  202. }
  203. // 11.1 Get Window Handle, https://w3c.github.io/webdriver/#get-window-handle
  204. Web::WebDriver::Response Session::get_window_handle()
  205. {
  206. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  207. TRY(check_for_open_top_level_browsing_context_or_return_error());
  208. // 2. Return success with data being the window handle associated with the current top-level browsing context.
  209. return JsonValue { m_current_window_handle };
  210. }
  211. // 11.2 Close Window, https://w3c.github.io/webdriver/#dfn-close-window
  212. ErrorOr<void, Variant<Web::WebDriver::Error, Error>> Session::close_window()
  213. {
  214. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  215. TRY(check_for_open_top_level_browsing_context_or_return_error());
  216. // 2. Close the current top-level browsing context.
  217. m_windows.remove(m_current_window_handle);
  218. // 3. If there are no more open top-level browsing contexts, then close the session.
  219. if (m_windows.is_empty()) {
  220. auto result = stop();
  221. if (result.is_error()) {
  222. return Variant<Web::WebDriver::Error, Error>(result.release_error());
  223. }
  224. }
  225. return {};
  226. }
  227. // 11.4 Get Window Handles, https://w3c.github.io/webdriver/#dfn-get-window-handles
  228. Web::WebDriver::Response Session::get_window_handles() const
  229. {
  230. // 1. Let handles be a JSON List.
  231. auto handles = JsonArray {};
  232. // 2. For each top-level browsing context in the remote end, push the associated window handle onto handles.
  233. for (auto const& window_handle : m_windows.keys())
  234. handles.append(window_handle);
  235. // 3. Return success with data handles.
  236. return JsonValue { handles };
  237. }
  238. static JsonValue serialize_rect(Gfx::IntRect const& rect)
  239. {
  240. JsonObject serialized_rect = {};
  241. serialized_rect.set("x", rect.x());
  242. serialized_rect.set("y", rect.y());
  243. serialized_rect.set("width", rect.width());
  244. serialized_rect.set("height", rect.height());
  245. return serialized_rect;
  246. }
  247. // https://w3c.github.io/webdriver/#dfn-get-a-known-connected-element
  248. static ErrorOr<i32, Web::WebDriver::Error> get_known_connected_element(StringView element_id)
  249. {
  250. // NOTE: The whole concept of "connected elements" is not implemented yet. See get_or_create_a_web_element_reference().
  251. // For now the element is only represented by its ID.
  252. auto maybe_element_id = element_id.to_int();
  253. if (!maybe_element_id.has_value())
  254. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Element ID is not an integer");
  255. return maybe_element_id.release_value();
  256. }
  257. // 12.4.4 Get Element CSS Value, https://w3c.github.io/webdriver/#dfn-get-element-css-value
  258. Web::WebDriver::Response Session::get_element_css_value(JsonValue const&, StringView parameter_element_id, StringView property_name)
  259. {
  260. // 1. If the current browsing context is no longer open, return error with error code no such window.
  261. TRY(check_for_open_top_level_browsing_context_or_return_error());
  262. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  263. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  264. auto element_id = TRY(get_known_connected_element(parameter_element_id));
  265. // 4. Let computed value be the result of the first matching condition:
  266. // -> current browsing context’s active document’s type is not "xml"
  267. // computed value of parameter property name from element’s style declarations. property name is obtained from url variables.
  268. // -> Otherwise
  269. // "" (empty string)
  270. auto active_documents_type = m_browser_connection->get_active_documents_type();
  271. if (active_documents_type == "xml")
  272. return JsonValue("");
  273. auto computed_value = m_browser_connection->get_computed_value_for_element(element_id, property_name);
  274. // 5. Return success with data computed value.
  275. return JsonValue(computed_value);
  276. }
  277. // 12.4.5 Get Element Text, https://w3c.github.io/webdriver/#dfn-get-element-text
  278. Web::WebDriver::Response Session::get_element_text(JsonValue const&, StringView parameter_element_id)
  279. {
  280. // 1. If the current browsing context is no longer open, return error with error code no such window.
  281. TRY(check_for_open_top_level_browsing_context_or_return_error());
  282. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  283. // FIXME: 3. Let element be the result of trying to get a known connected element with url variable element id.
  284. auto maybe_element_id = parameter_element_id.to_int();
  285. if (!maybe_element_id.has_value())
  286. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Element ID is not an i32");
  287. auto element_id = maybe_element_id.release_value();
  288. // 4. Let rendered text be the result of performing implementation-specific steps whose result is exactly the
  289. // same as the result of a Function.[[Call]](null, element) with bot.dom.getVisibleText as the this value.
  290. auto rendered_text = m_browser_connection->get_element_text(element_id);
  291. // 5. Return success with data rendered text.
  292. return JsonValue(rendered_text);
  293. }
  294. // 12.4.6 Get Element Tag Name, https://w3c.github.io/webdriver/#dfn-get-element-tag-name
  295. Web::WebDriver::Response Session::get_element_tag_name(JsonValue const&, StringView parameter_element_id)
  296. {
  297. // 1. If the current browsing context is no longer open, return error with error code no such window.
  298. TRY(check_for_open_top_level_browsing_context_or_return_error());
  299. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  300. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  301. auto element_id = TRY(get_known_connected_element(parameter_element_id));
  302. // 4. Let qualified name be the result of getting element’s tagName IDL attribute.
  303. auto qualified_name = m_browser_connection->get_element_tag_name(element_id);
  304. // 5. Return success with data qualified name.
  305. return JsonValue(qualified_name);
  306. }
  307. // 12.4.7 Get Element Rect, https://w3c.github.io/webdriver/#dfn-get-element-rect
  308. Web::WebDriver::Response Session::get_element_rect(StringView parameter_element_id)
  309. {
  310. // 1. If the current browsing context is no longer open, return error with error code no such window.
  311. TRY(check_for_open_top_level_browsing_context_or_return_error());
  312. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  313. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  314. auto element_id = TRY(get_known_connected_element(parameter_element_id));
  315. // 4. Calculate the absolute position of element and let it be coordinates.
  316. // 5. Let rect be element’s bounding rectangle.
  317. auto rect = m_browser_connection->get_element_rect(element_id);
  318. // 6. Let body be a new JSON Object initialized with:
  319. // "x"
  320. // The first value of coordinates.
  321. // "y"
  322. // The second value of coordinates.
  323. // "width"
  324. // Value of rect’s width dimension.
  325. // "height"
  326. // Value of rect’s height dimension.
  327. auto body = serialize_rect(rect);
  328. // 7. Return success with data body.
  329. return body;
  330. }
  331. // 12.4.8 Is Element Enabled, https://w3c.github.io/webdriver/#dfn-is-element-enabled
  332. Web::WebDriver::Response Session::is_element_enabled(StringView parameter_element_id)
  333. {
  334. // 1. If the current browsing context is no longer open, return error with error code no such window.
  335. TRY(check_for_open_top_level_browsing_context_or_return_error());
  336. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  337. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  338. auto element_id = TRY(get_known_connected_element(parameter_element_id));
  339. // 4. Let enabled be a boolean initially set to true if the current browsing context’s active document’s type is not "xml".
  340. // 5. Otherwise, let enabled to false and jump to the last step of this algorithm.
  341. // 6. Set enabled to false if a form control is disabled.
  342. auto enabled = m_browser_connection->is_element_enabled(element_id);
  343. // 7. Return success with data enabled.
  344. return JsonValue { enabled };
  345. }
  346. // 13.1 Get Page Source, https://w3c.github.io/webdriver/#dfn-get-page-source
  347. Web::WebDriver::Response Session::get_source()
  348. {
  349. // 1. If the current browsing context is no longer open, return error with error code no such window.
  350. TRY(check_for_open_top_level_browsing_context_or_return_error());
  351. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  352. // 3. Let source be the result of invoking the fragment serializing algorithm on a fictional node whose only child is the document element providing true for the require well-formed flag. If this causes an exception to be thrown, let source be null.
  353. // 4. Let source be the result of serializing to string the current browsing context active document, if source is null.
  354. // NOTE: Both of the above cases are handled in the remote WebContent process.
  355. auto source = m_browser_connection->serialize_source();
  356. // 5. Return success with data source.
  357. return JsonValue { source };
  358. }
  359. struct ScriptArguments {
  360. String script;
  361. JsonArray const& arguments;
  362. };
  363. // https://w3c.github.io/webdriver/#dfn-extract-the-script-arguments-from-a-request
  364. static ErrorOr<ScriptArguments, Web::WebDriver::Error> extract_the_script_arguments_from_a_request(JsonValue const& payload)
  365. {
  366. if (!payload.is_object())
  367. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload is not a JSON object");
  368. auto const& properties = payload.as_object();
  369. // 1. Let script be the result of getting a property named script from the parameters.
  370. // 2. If script is not a String, return error with error code invalid argument.
  371. if (!properties.has_string("script"sv))
  372. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have a 'script' string property");
  373. auto script = properties.get("script"sv).as_string();
  374. // 3. Let args be the result of getting a property named args from the parameters.
  375. // 4. If args is not an Array return error with error code invalid argument.
  376. if (!properties.has_array("args"sv))
  377. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have an 'args' string property");
  378. auto const& args = properties.get("args"sv).as_array();
  379. // 5. Let arguments be the result of calling the JSON deserialize algorithm with arguments args.
  380. // NOTE: We forward the JSON array to the Browser and then WebContent process over IPC, so this is not necessary.
  381. // 6. Return success with data script and arguments.
  382. return ScriptArguments { script, args };
  383. }
  384. // 13.2.1 Execute Script, https://w3c.github.io/webdriver/#dfn-execute-script
  385. Web::WebDriver::Response Session::execute_script(JsonValue const& payload)
  386. {
  387. // 1. Let body and arguments be the result of trying to extract the script arguments from a request with argument parameters.
  388. auto const& [body, arguments] = TRY(extract_the_script_arguments_from_a_request(payload));
  389. // 2. If the current browsing context is no longer open, return error with error code no such window.
  390. TRY(check_for_open_top_level_browsing_context_or_return_error());
  391. // FIXME: 3. Handle any user prompts, and return its value if it is an error.
  392. // 4., 5.1-5.3.
  393. Vector<String> json_arguments;
  394. arguments.for_each([&](JsonValue const& json_value) {
  395. // NOTE: serialized() instead of to_string() ensures proper quoting.
  396. json_arguments.append(json_value.serialized<StringBuilder>());
  397. });
  398. dbgln("Executing script with 'args': [{}] / 'body':\n{}", String::join(", "sv, json_arguments), body);
  399. auto execute_script_response = m_browser_connection->execute_script(body, json_arguments, m_timeouts_configuration.script_timeout, false);
  400. dbgln("Executing script returned: {}", execute_script_response.json_result());
  401. // NOTE: This is assumed to be a valid JSON value.
  402. auto result = MUST(JsonValue::from_string(execute_script_response.json_result()));
  403. switch (execute_script_response.result_type()) {
  404. // 6. If promise is still pending and the session script timeout is reached, return error with error code script timeout.
  405. case Web::WebDriver::ExecuteScriptResultType::Timeout:
  406. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::ScriptTimeoutError, "Script timed out");
  407. // 7. Upon fulfillment of promise with value v, let result be a JSON clone of v, and return success with data result.
  408. case Web::WebDriver::ExecuteScriptResultType::PromiseResolved:
  409. return result;
  410. // 8. Upon rejection of promise with reason r, let result be a JSON clone of r, and return error with error code javascript error and data result.
  411. case Web::WebDriver::ExecuteScriptResultType::PromiseRejected:
  412. case Web::WebDriver::ExecuteScriptResultType::JavaScriptError:
  413. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::JavascriptError, "Script returned an error", move(result));
  414. default:
  415. VERIFY_NOT_REACHED();
  416. }
  417. }
  418. // 13.2.2 Execute Async Script, https://w3c.github.io/webdriver/#dfn-execute-async-script
  419. Web::WebDriver::Response Session::execute_async_script(JsonValue const& parameters)
  420. {
  421. // 1. Let body and arguments by the result of trying to extract the script arguments from a request with argument parameters.
  422. auto [body, arguments] = TRY(extract_the_script_arguments_from_a_request(parameters));
  423. // 2. If the current browsing context is no longer open, return error with error code no such window.
  424. TRY(check_for_open_top_level_browsing_context_or_return_error());
  425. // FIXME: 3. Handle any user prompts, and return its value if it is an error.
  426. // 4., 5.1-5.11.
  427. Vector<String> json_arguments;
  428. arguments.for_each([&](JsonValue const& json_value) {
  429. // NOTE: serialized() instead of to_string() ensures proper quoting.
  430. json_arguments.append(json_value.serialized<StringBuilder>());
  431. });
  432. dbgln("Executing async script with 'args': [{}] / 'body':\n{}", String::join(", "sv, json_arguments), body);
  433. auto execute_script_response = m_browser_connection->execute_script(body, json_arguments, m_timeouts_configuration.script_timeout, true);
  434. dbgln("Executing async script returned: {}", execute_script_response.json_result());
  435. // NOTE: This is assumed to be a valid JSON value.
  436. auto result = MUST(JsonValue::from_string(execute_script_response.json_result()));
  437. switch (execute_script_response.result_type()) {
  438. // 6. If promise is still pending and the session script timeout is reached, return error with error code script timeout.
  439. case Web::WebDriver::ExecuteScriptResultType::Timeout:
  440. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::ScriptTimeoutError, "Script timed out");
  441. // 7. Upon fulfillment of promise with value v, let result be a JSON clone of v, and return success with data result.
  442. case Web::WebDriver::ExecuteScriptResultType::PromiseResolved:
  443. return result;
  444. // 8. Upon rejection of promise with reason r, let result be a JSON clone of r, and return error with error code javascript error and data result.
  445. case Web::WebDriver::ExecuteScriptResultType::PromiseRejected:
  446. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::JavascriptError, "Script returned an error", move(result));
  447. default:
  448. VERIFY_NOT_REACHED();
  449. }
  450. }
  451. // https://w3c.github.io/webdriver/#dfn-serialized-cookie
  452. static JsonObject serialize_cookie(Web::Cookie::Cookie const& cookie)
  453. {
  454. JsonObject serialized_cookie = {};
  455. serialized_cookie.set("name", cookie.name);
  456. serialized_cookie.set("value", cookie.value);
  457. serialized_cookie.set("path", cookie.path);
  458. serialized_cookie.set("domain", cookie.domain);
  459. serialized_cookie.set("secure", cookie.secure);
  460. serialized_cookie.set("httpOnly", cookie.http_only);
  461. serialized_cookie.set("expiry", cookie.expiry_time.timestamp());
  462. // FIXME: Add sameSite to Cookie and serialize it here too.
  463. return serialized_cookie;
  464. }
  465. // 14.1 Get All Cookies, https://w3c.github.io/webdriver/#dfn-get-all-cookies
  466. Web::WebDriver::Response Session::get_all_cookies()
  467. {
  468. // 1. If the current browsing context is no longer open, return error with error code no such window.
  469. TRY(check_for_open_top_level_browsing_context_or_return_error());
  470. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  471. // 3. Let cookies be a new JSON List.
  472. JsonArray cookies = {};
  473. // 4. For each cookie in all associated cookies of the current browsing context’s active document:
  474. for (auto const& cookie : m_browser_connection->get_all_cookies()) {
  475. // 1. Let serialized cookie be the result of serializing cookie.
  476. auto serialized_cookie = serialize_cookie(cookie);
  477. // 2. Append serialized cookie to cookies
  478. cookies.append(serialized_cookie);
  479. }
  480. // 5. Return success with data cookies.
  481. return JsonValue(cookies);
  482. }
  483. // 14.2 Get Named Cookie, https://w3c.github.io/webdriver/#dfn-get-named-cookie
  484. Web::WebDriver::Response Session::get_named_cookie(String const& name)
  485. {
  486. // 1. If the current browsing context is no longer open, return error with error code no such window.
  487. TRY(check_for_open_top_level_browsing_context_or_return_error());
  488. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  489. // 3. If the url variable name is equal to a cookie’s cookie name amongst all associated cookies of the
  490. // current browsing context’s active document, return success with the serialized cookie as data.
  491. auto maybe_cookie = m_browser_connection->get_named_cookie(name);
  492. if (maybe_cookie.has_value()) {
  493. auto cookie = maybe_cookie.release_value();
  494. auto serialized_cookie = serialize_cookie(cookie);
  495. return JsonValue(serialized_cookie);
  496. }
  497. // 4. Otherwise, return error with error code no such cookie.
  498. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchCookie, "Cookie not found");
  499. }
  500. // 14.3 Add Cookie, https://w3c.github.io/webdriver/#dfn-adding-a-cookie
  501. Web::WebDriver::Response Session::add_cookie(JsonValue const& payload)
  502. {
  503. // 1. Let data be the result of getting a property named cookie from the parameters argument.
  504. if (!payload.is_object() || !payload.as_object().has_object("cookie"sv))
  505. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have a cookie object");
  506. auto const& maybe_data = payload.as_object().get("cookie"sv);
  507. // 2. If data is not a JSON Object with all the required (non-optional) JSON keys listed in the table for cookie conversion,
  508. // return error with error code invalid argument.
  509. // NOTE: Table is here: https://w3c.github.io/webdriver/#dfn-table-for-cookie-conversion
  510. if (!maybe_data.is_object())
  511. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Value \"cookie\' is not an object");
  512. auto const& data = maybe_data.as_object();
  513. if (!data.has("name"sv) || !data.has("value"sv))
  514. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object doesn't contain all required keys");
  515. // 3. If the current browsing context is no longer open, return error with error code no such window.
  516. TRY(check_for_open_top_level_browsing_context_or_return_error());
  517. // FIXME: 4. Handle any user prompts, and return its value if it is an error.
  518. // FIXME: 5. If the current browsing context’s document element is a cookie-averse Document object,
  519. // return error with error code invalid cookie domain.
  520. // 6. If cookie name or cookie value is null,
  521. // FIXME: cookie domain is not equal to the current browsing context’s active document’s domain,
  522. // cookie secure only or cookie HTTP only are not boolean types,
  523. // or cookie expiry time is not an integer type, or it less than 0 or greater than the maximum safe integer,
  524. // return error with error code invalid argument.
  525. if (data.get("name"sv).is_null() || data.get("value"sv).is_null())
  526. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: name or value are null");
  527. if (data.has("secure"sv) && !data.get("secure"sv).is_bool())
  528. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: secure is not bool");
  529. if (data.has("httpOnly"sv) && !data.get("httpOnly"sv).is_bool())
  530. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: httpOnly is not bool");
  531. Optional<Core::DateTime> expiry_time;
  532. if (data.has("expiry"sv)) {
  533. auto expiry_argument = data.get("expiry"sv);
  534. if (!expiry_argument.is_u32()) {
  535. // NOTE: less than 0 or greater than safe integer are handled by the JSON parser
  536. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: expiry is not u32");
  537. }
  538. expiry_time = Core::DateTime::from_timestamp(expiry_argument.as_u32());
  539. }
  540. // 7. Create a cookie in the cookie store associated with the active document’s address using
  541. // cookie name name, cookie value value, and an attribute-value list of the following cookie concepts
  542. // listed in the table for cookie conversion from data:
  543. Web::Cookie::ParsedCookie cookie;
  544. if (auto name_attribute = data.get("name"sv); name_attribute.is_string())
  545. cookie.name = name_attribute.as_string();
  546. else
  547. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect name attribute to be string");
  548. if (auto value_attribute = data.get("value"sv); value_attribute.is_string())
  549. cookie.value = value_attribute.as_string();
  550. else
  551. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect value attribute to be string");
  552. // Cookie path
  553. // The value if the entry exists, otherwise "/".
  554. if (data.has("path"sv)) {
  555. if (auto path_attribute = data.get("path"sv); path_attribute.is_string())
  556. cookie.path = path_attribute.as_string();
  557. else
  558. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect path attribute to be string");
  559. } else {
  560. cookie.path = "/";
  561. }
  562. // Cookie domain
  563. // The value if the entry exists, otherwise the current browsing context’s active document’s URL domain.
  564. // NOTE: The otherwise case is handled by the CookieJar
  565. if (data.has("domain"sv)) {
  566. if (auto domain_attribute = data.get("domain"sv); domain_attribute.is_string())
  567. cookie.domain = domain_attribute.as_string();
  568. else
  569. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect domain attribute to be string");
  570. }
  571. // Cookie secure only
  572. // The value if the entry exists, otherwise false.
  573. if (data.has("secure"sv)) {
  574. cookie.secure_attribute_present = data.get("secure"sv).as_bool();
  575. } else {
  576. cookie.secure_attribute_present = false;
  577. }
  578. // Cookie HTTP only
  579. // The value if the entry exists, otherwise false.
  580. if (data.has("httpOnly"sv)) {
  581. cookie.http_only_attribute_present = data.get("httpOnly"sv).as_bool();
  582. } else {
  583. cookie.http_only_attribute_present = false;
  584. }
  585. // Cookie expiry time
  586. // The value if the entry exists, otherwise leave unset to indicate that this is a session cookie.
  587. cookie.expiry_time_from_expires_attribute = expiry_time;
  588. // FIXME: Cookie same site
  589. // The value if the entry exists, otherwise leave unset to indicate that no same site policy is defined.
  590. m_browser_connection->async_add_cookie(move(cookie));
  591. // If there is an error during this step, return error with error code unable to set cookie.
  592. // NOTE: This probably should only apply to the actual setting of the cookie in the Browser,
  593. // which cannot fail in our case.
  594. // Thus, the error-codes used above are 400 "invalid argument".
  595. // 8. Return success with data null.
  596. return JsonValue();
  597. }
  598. // https://w3c.github.io/webdriver/#dfn-delete-cookies
  599. void Session::delete_cookies(Optional<StringView> const& name)
  600. {
  601. // For each cookie among all associated cookies of the current browsing context’s active document,
  602. // run the substeps of the first matching condition:
  603. for (auto& cookie : m_browser_connection->get_all_cookies()) {
  604. // -> name is undefined
  605. // -> name is equal to cookie name
  606. if (!name.has_value() || name.value() == cookie.name) {
  607. // Set the cookie expiry time to a Unix timestamp in the past.
  608. cookie.expiry_time = Core::DateTime::from_timestamp(0);
  609. m_browser_connection->async_update_cookie(cookie);
  610. }
  611. // -> Otherwise
  612. // Do nothing.
  613. }
  614. }
  615. // 14.4 Delete Cookie, https://w3c.github.io/webdriver/#dfn-delete-cookie
  616. Web::WebDriver::Response Session::delete_cookie(StringView name)
  617. {
  618. // 1. If the current browsing context is no longer open, return error with error code no such window.
  619. TRY(check_for_open_top_level_browsing_context_or_return_error());
  620. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  621. // 3. Delete cookies using the url variable name parameter as the filter argument.
  622. delete_cookies(name);
  623. // 4. Return success with data null.
  624. return JsonValue();
  625. }
  626. // 14.5 Delete All Cookies, https://w3c.github.io/webdriver/#dfn-delete-all-cookies
  627. Web::WebDriver::Response Session::delete_all_cookies()
  628. {
  629. // 1. If the current browsing context is no longer open, return error with error code no such window.
  630. TRY(check_for_open_top_level_browsing_context_or_return_error());
  631. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  632. // 3. Delete cookies, giving no filtering argument.
  633. delete_cookies();
  634. // 4. Return success with data null.
  635. return JsonValue();
  636. }
  637. // https://w3c.github.io/webdriver/#dfn-encoding-a-canvas-as-base64
  638. static ErrorOr<String, Web::WebDriver::Error> encode_bitmap_as_canvas_element(Gfx::Bitmap const& bitmap)
  639. {
  640. // FIXME: 1. If the canvas element’s bitmap’s origin-clean flag is set to false, return error with error code unable to capture screen.
  641. // 2. If the canvas element’s bitmap has no pixels (i.e. either its horizontal dimension or vertical dimension is zero) then return error with error code unable to capture screen.
  642. if (bitmap.width() == 0 || bitmap.height() == 0)
  643. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnableToCaptureScreen, "Captured screenshot is empty"sv);
  644. // 3. Let file be a serialization of the canvas element’s bitmap as a file, using "image/png" as an argument.
  645. auto file = Gfx::PNGWriter::encode(bitmap);
  646. // 4. Let data url be a data: URL representing file. [RFC2397]
  647. auto data_url = AK::URL::create_with_data("image/png"sv, encode_base64(file), true).to_string();
  648. // 5. Let index be the index of "," in data url.
  649. auto index = data_url.find(',');
  650. VERIFY(index.has_value());
  651. // 6. Let encoded string be a substring of data url using (index + 1) as the start argument.
  652. auto encoded_string = data_url.substring(*index + 1);
  653. // 7. Return success with data encoded string.
  654. return encoded_string;
  655. }
  656. // 17.1 Take Screenshot, https://w3c.github.io/webdriver/#take-screenshot
  657. Web::WebDriver::Response Session::take_screenshot()
  658. {
  659. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  660. TRY(check_for_open_top_level_browsing_context_or_return_error());
  661. // 2. When the user agent is next to run the animation frame callbacks:
  662. // a. Let root rect be the current top-level browsing context’s document element’s rectangle.
  663. // b. Let screenshot result be the result of trying to call draw a bounding box from the framebuffer, given root rect as an argument.
  664. auto screenshot = m_browser_connection->take_screenshot();
  665. if (!screenshot.is_valid())
  666. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnableToCaptureScreen, "Unable to capture screenshot"sv);
  667. // c. Let canvas be a canvas element of screenshot result’s data.
  668. // d. Let encoding result be the result of trying encoding a canvas as Base64 canvas.
  669. // e. Let encoded string be encoding result’s data.
  670. auto encoded_string = TRY(encode_bitmap_as_canvas_element(*screenshot.bitmap()));
  671. // 3. Return success with data encoded string.
  672. return JsonValue { encoded_string };
  673. }
  674. // 17.2 Take Element Screenshot, https://w3c.github.io/webdriver/#dfn-take-element-screenshot
  675. Web::WebDriver::Response Session::take_element_screenshot(StringView parameter_element_id)
  676. {
  677. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  678. TRY(check_for_open_top_level_browsing_context_or_return_error());
  679. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  680. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  681. auto element_id = TRY(get_known_connected_element(parameter_element_id));
  682. // 4. Scroll into view the element.
  683. m_browser_connection->scroll_element_into_view(element_id);
  684. // 5. When the user agent is next to run the animation frame callbacks:
  685. // a. Let element rect be element’s rectangle.
  686. // b. Let screenshot result be the result of trying to call draw a bounding box from the framebuffer, given element rect as an argument.
  687. auto screenshot = m_browser_connection->take_element_screenshot(element_id);
  688. if (!screenshot.is_valid())
  689. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnableToCaptureScreen, "Unable to capture screenshot"sv);
  690. // c. Let canvas be a canvas element of screenshot result’s data.
  691. // d. Let encoding result be the result of trying encoding a canvas as Base64 canvas.
  692. // e. Let encoded string be encoding result’s data.
  693. auto encoded_string = TRY(encode_bitmap_as_canvas_element(*screenshot.bitmap()));
  694. // 6. Return success with data encoded string.
  695. return JsonValue { encoded_string };
  696. }
  697. }