Session.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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. // https://w3c.github.io/webdriver/#dfn-get-a-known-connected-element
  239. static ErrorOr<i32, Web::WebDriver::Error> get_known_connected_element(StringView element_id)
  240. {
  241. // NOTE: The whole concept of "connected elements" is not implemented yet. See get_or_create_a_web_element_reference().
  242. // For now the element is only represented by its ID.
  243. auto maybe_element_id = element_id.to_int();
  244. if (!maybe_element_id.has_value())
  245. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Element ID is not an integer");
  246. return maybe_element_id.release_value();
  247. }
  248. // 12.4.8 Is Element Enabled, https://w3c.github.io/webdriver/#dfn-is-element-enabled
  249. Web::WebDriver::Response Session::is_element_enabled(StringView parameter_element_id)
  250. {
  251. // 1. If the current browsing context is no longer open, return error with error code no such window.
  252. TRY(check_for_open_top_level_browsing_context_or_return_error());
  253. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  254. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  255. auto element_id = TRY(get_known_connected_element(parameter_element_id));
  256. // 4. Let enabled be a boolean initially set to true if the current browsing context’s active document’s type is not "xml".
  257. // 5. Otherwise, let enabled to false and jump to the last step of this algorithm.
  258. // 6. Set enabled to false if a form control is disabled.
  259. auto enabled = m_browser_connection->is_element_enabled(element_id);
  260. // 7. Return success with data enabled.
  261. return JsonValue { enabled };
  262. }
  263. // 13.1 Get Page Source, https://w3c.github.io/webdriver/#dfn-get-page-source
  264. Web::WebDriver::Response Session::get_source()
  265. {
  266. // 1. If the current browsing context is no longer open, return error with error code no such window.
  267. TRY(check_for_open_top_level_browsing_context_or_return_error());
  268. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  269. // 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.
  270. // 4. Let source be the result of serializing to string the current browsing context active document, if source is null.
  271. // NOTE: Both of the above cases are handled in the remote WebContent process.
  272. auto source = m_browser_connection->serialize_source();
  273. // 5. Return success with data source.
  274. return JsonValue { source };
  275. }
  276. struct ScriptArguments {
  277. String script;
  278. JsonArray const& arguments;
  279. };
  280. // https://w3c.github.io/webdriver/#dfn-extract-the-script-arguments-from-a-request
  281. static ErrorOr<ScriptArguments, Web::WebDriver::Error> extract_the_script_arguments_from_a_request(JsonValue const& payload)
  282. {
  283. if (!payload.is_object())
  284. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload is not a JSON object");
  285. auto const& properties = payload.as_object();
  286. // 1. Let script be the result of getting a property named script from the parameters.
  287. // 2. If script is not a String, return error with error code invalid argument.
  288. if (!properties.has_string("script"sv))
  289. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have a 'script' string property");
  290. auto script = properties.get("script"sv).as_string();
  291. // 3. Let args be the result of getting a property named args from the parameters.
  292. // 4. If args is not an Array return error with error code invalid argument.
  293. if (!properties.has_array("args"sv))
  294. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have an 'args' string property");
  295. auto const& args = properties.get("args"sv).as_array();
  296. // 5. Let arguments be the result of calling the JSON deserialize algorithm with arguments args.
  297. // NOTE: We forward the JSON array to the Browser and then WebContent process over IPC, so this is not necessary.
  298. // 6. Return success with data script and arguments.
  299. return ScriptArguments { script, args };
  300. }
  301. // 13.2.1 Execute Script, https://w3c.github.io/webdriver/#dfn-execute-script
  302. Web::WebDriver::Response Session::execute_script(JsonValue const& payload)
  303. {
  304. // 1. Let body and arguments be the result of trying to extract the script arguments from a request with argument parameters.
  305. auto const& [body, arguments] = TRY(extract_the_script_arguments_from_a_request(payload));
  306. // 2. If the current browsing context is no longer open, return error with error code no such window.
  307. TRY(check_for_open_top_level_browsing_context_or_return_error());
  308. // FIXME: 3. Handle any user prompts, and return its value if it is an error.
  309. // 4., 5.1-5.3.
  310. Vector<String> json_arguments;
  311. arguments.for_each([&](JsonValue const& json_value) {
  312. // NOTE: serialized() instead of to_string() ensures proper quoting.
  313. json_arguments.append(json_value.serialized<StringBuilder>());
  314. });
  315. dbgln("Executing script with 'args': [{}] / 'body':\n{}", String::join(", "sv, json_arguments), body);
  316. auto execute_script_response = m_browser_connection->execute_script(body, json_arguments, m_timeouts_configuration.script_timeout, false);
  317. dbgln("Executing script returned: {}", execute_script_response.json_result());
  318. // NOTE: This is assumed to be a valid JSON value.
  319. auto result = MUST(JsonValue::from_string(execute_script_response.json_result()));
  320. switch (execute_script_response.result_type()) {
  321. // 6. If promise is still pending and the session script timeout is reached, return error with error code script timeout.
  322. case Web::WebDriver::ExecuteScriptResultType::Timeout:
  323. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::ScriptTimeoutError, "Script timed out");
  324. // 7. Upon fulfillment of promise with value v, let result be a JSON clone of v, and return success with data result.
  325. case Web::WebDriver::ExecuteScriptResultType::PromiseResolved:
  326. return result;
  327. // 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.
  328. case Web::WebDriver::ExecuteScriptResultType::PromiseRejected:
  329. case Web::WebDriver::ExecuteScriptResultType::JavaScriptError:
  330. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::JavascriptError, "Script returned an error", move(result));
  331. default:
  332. VERIFY_NOT_REACHED();
  333. }
  334. }
  335. // 13.2.2 Execute Async Script, https://w3c.github.io/webdriver/#dfn-execute-async-script
  336. Web::WebDriver::Response Session::execute_async_script(JsonValue const& parameters)
  337. {
  338. // 1. Let body and arguments by the result of trying to extract the script arguments from a request with argument parameters.
  339. auto [body, arguments] = TRY(extract_the_script_arguments_from_a_request(parameters));
  340. // 2. If the current browsing context is no longer open, return error with error code no such window.
  341. TRY(check_for_open_top_level_browsing_context_or_return_error());
  342. // FIXME: 3. Handle any user prompts, and return its value if it is an error.
  343. // 4., 5.1-5.11.
  344. Vector<String> json_arguments;
  345. arguments.for_each([&](JsonValue const& json_value) {
  346. // NOTE: serialized() instead of to_string() ensures proper quoting.
  347. json_arguments.append(json_value.serialized<StringBuilder>());
  348. });
  349. dbgln("Executing async script with 'args': [{}] / 'body':\n{}", String::join(", "sv, json_arguments), body);
  350. auto execute_script_response = m_browser_connection->execute_script(body, json_arguments, m_timeouts_configuration.script_timeout, true);
  351. dbgln("Executing async script returned: {}", execute_script_response.json_result());
  352. // NOTE: This is assumed to be a valid JSON value.
  353. auto result = MUST(JsonValue::from_string(execute_script_response.json_result()));
  354. switch (execute_script_response.result_type()) {
  355. // 6. If promise is still pending and the session script timeout is reached, return error with error code script timeout.
  356. case Web::WebDriver::ExecuteScriptResultType::Timeout:
  357. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::ScriptTimeoutError, "Script timed out");
  358. // 7. Upon fulfillment of promise with value v, let result be a JSON clone of v, and return success with data result.
  359. case Web::WebDriver::ExecuteScriptResultType::PromiseResolved:
  360. return result;
  361. // 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.
  362. case Web::WebDriver::ExecuteScriptResultType::PromiseRejected:
  363. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::JavascriptError, "Script returned an error", move(result));
  364. default:
  365. VERIFY_NOT_REACHED();
  366. }
  367. }
  368. // https://w3c.github.io/webdriver/#dfn-serialized-cookie
  369. static JsonObject serialize_cookie(Web::Cookie::Cookie const& cookie)
  370. {
  371. JsonObject serialized_cookie = {};
  372. serialized_cookie.set("name", cookie.name);
  373. serialized_cookie.set("value", cookie.value);
  374. serialized_cookie.set("path", cookie.path);
  375. serialized_cookie.set("domain", cookie.domain);
  376. serialized_cookie.set("secure", cookie.secure);
  377. serialized_cookie.set("httpOnly", cookie.http_only);
  378. serialized_cookie.set("expiry", cookie.expiry_time.timestamp());
  379. // FIXME: Add sameSite to Cookie and serialize it here too.
  380. return serialized_cookie;
  381. }
  382. // 14.1 Get All Cookies, https://w3c.github.io/webdriver/#dfn-get-all-cookies
  383. Web::WebDriver::Response Session::get_all_cookies()
  384. {
  385. // 1. If the current browsing context is no longer open, return error with error code no such window.
  386. TRY(check_for_open_top_level_browsing_context_or_return_error());
  387. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  388. // 3. Let cookies be a new JSON List.
  389. JsonArray cookies = {};
  390. // 4. For each cookie in all associated cookies of the current browsing context’s active document:
  391. for (auto const& cookie : m_browser_connection->get_all_cookies()) {
  392. // 1. Let serialized cookie be the result of serializing cookie.
  393. auto serialized_cookie = serialize_cookie(cookie);
  394. // 2. Append serialized cookie to cookies
  395. cookies.append(serialized_cookie);
  396. }
  397. // 5. Return success with data cookies.
  398. return JsonValue(cookies);
  399. }
  400. // 14.2 Get Named Cookie, https://w3c.github.io/webdriver/#dfn-get-named-cookie
  401. Web::WebDriver::Response Session::get_named_cookie(String const& name)
  402. {
  403. // 1. If the current browsing context is no longer open, return error with error code no such window.
  404. TRY(check_for_open_top_level_browsing_context_or_return_error());
  405. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  406. // 3. If the url variable name is equal to a cookie’s cookie name amongst all associated cookies of the
  407. // current browsing context’s active document, return success with the serialized cookie as data.
  408. auto maybe_cookie = m_browser_connection->get_named_cookie(name);
  409. if (maybe_cookie.has_value()) {
  410. auto cookie = maybe_cookie.release_value();
  411. auto serialized_cookie = serialize_cookie(cookie);
  412. return JsonValue(serialized_cookie);
  413. }
  414. // 4. Otherwise, return error with error code no such cookie.
  415. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchCookie, "Cookie not found");
  416. }
  417. // 14.3 Add Cookie, https://w3c.github.io/webdriver/#dfn-adding-a-cookie
  418. Web::WebDriver::Response Session::add_cookie(JsonValue const& payload)
  419. {
  420. // 1. Let data be the result of getting a property named cookie from the parameters argument.
  421. if (!payload.is_object() || !payload.as_object().has_object("cookie"sv))
  422. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have a cookie object");
  423. auto const& maybe_data = payload.as_object().get("cookie"sv);
  424. // 2. If data is not a JSON Object with all the required (non-optional) JSON keys listed in the table for cookie conversion,
  425. // return error with error code invalid argument.
  426. // NOTE: Table is here: https://w3c.github.io/webdriver/#dfn-table-for-cookie-conversion
  427. if (!maybe_data.is_object())
  428. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Value \"cookie\' is not an object");
  429. auto const& data = maybe_data.as_object();
  430. if (!data.has("name"sv) || !data.has("value"sv))
  431. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object doesn't contain all required keys");
  432. // 3. If the current browsing context is no longer open, return error with error code no such window.
  433. TRY(check_for_open_top_level_browsing_context_or_return_error());
  434. // FIXME: 4. Handle any user prompts, and return its value if it is an error.
  435. // FIXME: 5. If the current browsing context’s document element is a cookie-averse Document object,
  436. // return error with error code invalid cookie domain.
  437. // 6. If cookie name or cookie value is null,
  438. // FIXME: cookie domain is not equal to the current browsing context’s active document’s domain,
  439. // cookie secure only or cookie HTTP only are not boolean types,
  440. // or cookie expiry time is not an integer type, or it less than 0 or greater than the maximum safe integer,
  441. // return error with error code invalid argument.
  442. if (data.get("name"sv).is_null() || data.get("value"sv).is_null())
  443. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: name or value are null");
  444. if (data.has("secure"sv) && !data.get("secure"sv).is_bool())
  445. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: secure is not bool");
  446. if (data.has("httpOnly"sv) && !data.get("httpOnly"sv).is_bool())
  447. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: httpOnly is not bool");
  448. Optional<Core::DateTime> expiry_time;
  449. if (data.has("expiry"sv)) {
  450. auto expiry_argument = data.get("expiry"sv);
  451. if (!expiry_argument.is_u32()) {
  452. // NOTE: less than 0 or greater than safe integer are handled by the JSON parser
  453. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: expiry is not u32");
  454. }
  455. expiry_time = Core::DateTime::from_timestamp(expiry_argument.as_u32());
  456. }
  457. // 7. Create a cookie in the cookie store associated with the active document’s address using
  458. // cookie name name, cookie value value, and an attribute-value list of the following cookie concepts
  459. // listed in the table for cookie conversion from data:
  460. Web::Cookie::ParsedCookie cookie;
  461. if (auto name_attribute = data.get("name"sv); name_attribute.is_string())
  462. cookie.name = name_attribute.as_string();
  463. else
  464. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect name attribute to be string");
  465. if (auto value_attribute = data.get("value"sv); value_attribute.is_string())
  466. cookie.value = value_attribute.as_string();
  467. else
  468. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect value attribute to be string");
  469. // Cookie path
  470. // The value if the entry exists, otherwise "/".
  471. if (data.has("path"sv)) {
  472. if (auto path_attribute = data.get("path"sv); path_attribute.is_string())
  473. cookie.path = path_attribute.as_string();
  474. else
  475. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect path attribute to be string");
  476. } else {
  477. cookie.path = "/";
  478. }
  479. // Cookie domain
  480. // The value if the entry exists, otherwise the current browsing context’s active document’s URL domain.
  481. // NOTE: The otherwise case is handled by the CookieJar
  482. if (data.has("domain"sv)) {
  483. if (auto domain_attribute = data.get("domain"sv); domain_attribute.is_string())
  484. cookie.domain = domain_attribute.as_string();
  485. else
  486. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect domain attribute to be string");
  487. }
  488. // Cookie secure only
  489. // The value if the entry exists, otherwise false.
  490. if (data.has("secure"sv)) {
  491. cookie.secure_attribute_present = data.get("secure"sv).as_bool();
  492. } else {
  493. cookie.secure_attribute_present = false;
  494. }
  495. // Cookie HTTP only
  496. // The value if the entry exists, otherwise false.
  497. if (data.has("httpOnly"sv)) {
  498. cookie.http_only_attribute_present = data.get("httpOnly"sv).as_bool();
  499. } else {
  500. cookie.http_only_attribute_present = false;
  501. }
  502. // Cookie expiry time
  503. // The value if the entry exists, otherwise leave unset to indicate that this is a session cookie.
  504. cookie.expiry_time_from_expires_attribute = expiry_time;
  505. // FIXME: Cookie same site
  506. // The value if the entry exists, otherwise leave unset to indicate that no same site policy is defined.
  507. m_browser_connection->async_add_cookie(move(cookie));
  508. // If there is an error during this step, return error with error code unable to set cookie.
  509. // NOTE: This probably should only apply to the actual setting of the cookie in the Browser,
  510. // which cannot fail in our case.
  511. // Thus, the error-codes used above are 400 "invalid argument".
  512. // 8. Return success with data null.
  513. return JsonValue();
  514. }
  515. // https://w3c.github.io/webdriver/#dfn-delete-cookies
  516. void Session::delete_cookies(Optional<StringView> const& name)
  517. {
  518. // For each cookie among all associated cookies of the current browsing context’s active document,
  519. // run the substeps of the first matching condition:
  520. for (auto& cookie : m_browser_connection->get_all_cookies()) {
  521. // -> name is undefined
  522. // -> name is equal to cookie name
  523. if (!name.has_value() || name.value() == cookie.name) {
  524. // Set the cookie expiry time to a Unix timestamp in the past.
  525. cookie.expiry_time = Core::DateTime::from_timestamp(0);
  526. m_browser_connection->async_update_cookie(cookie);
  527. }
  528. // -> Otherwise
  529. // Do nothing.
  530. }
  531. }
  532. // 14.4 Delete Cookie, https://w3c.github.io/webdriver/#dfn-delete-cookie
  533. Web::WebDriver::Response Session::delete_cookie(StringView name)
  534. {
  535. // 1. If the current browsing context is no longer open, return error with error code no such window.
  536. TRY(check_for_open_top_level_browsing_context_or_return_error());
  537. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  538. // 3. Delete cookies using the url variable name parameter as the filter argument.
  539. delete_cookies(name);
  540. // 4. Return success with data null.
  541. return JsonValue();
  542. }
  543. // 14.5 Delete All Cookies, https://w3c.github.io/webdriver/#dfn-delete-all-cookies
  544. Web::WebDriver::Response Session::delete_all_cookies()
  545. {
  546. // 1. If the current browsing context is no longer open, return error with error code no such window.
  547. TRY(check_for_open_top_level_browsing_context_or_return_error());
  548. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  549. // 3. Delete cookies, giving no filtering argument.
  550. delete_cookies();
  551. // 4. Return success with data null.
  552. return JsonValue();
  553. }
  554. // https://w3c.github.io/webdriver/#dfn-encoding-a-canvas-as-base64
  555. static ErrorOr<String, Web::WebDriver::Error> encode_bitmap_as_canvas_element(Gfx::Bitmap const& bitmap)
  556. {
  557. // 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.
  558. // 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.
  559. if (bitmap.width() == 0 || bitmap.height() == 0)
  560. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnableToCaptureScreen, "Captured screenshot is empty"sv);
  561. // 3. Let file be a serialization of the canvas element’s bitmap as a file, using "image/png" as an argument.
  562. auto file = Gfx::PNGWriter::encode(bitmap);
  563. // 4. Let data url be a data: URL representing file. [RFC2397]
  564. auto data_url = AK::URL::create_with_data("image/png"sv, encode_base64(file), true).to_string();
  565. // 5. Let index be the index of "," in data url.
  566. auto index = data_url.find(',');
  567. VERIFY(index.has_value());
  568. // 6. Let encoded string be a substring of data url using (index + 1) as the start argument.
  569. auto encoded_string = data_url.substring(*index + 1);
  570. // 7. Return success with data encoded string.
  571. return encoded_string;
  572. }
  573. // 17.1 Take Screenshot, https://w3c.github.io/webdriver/#take-screenshot
  574. Web::WebDriver::Response Session::take_screenshot()
  575. {
  576. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  577. TRY(check_for_open_top_level_browsing_context_or_return_error());
  578. // 2. When the user agent is next to run the animation frame callbacks:
  579. // a. Let root rect be the current top-level browsing context’s document element’s rectangle.
  580. // b. Let screenshot result be the result of trying to call draw a bounding box from the framebuffer, given root rect as an argument.
  581. auto screenshot = m_browser_connection->take_screenshot();
  582. if (!screenshot.is_valid())
  583. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnableToCaptureScreen, "Unable to capture screenshot"sv);
  584. // c. Let canvas be a canvas element of screenshot result’s data.
  585. // d. Let encoding result be the result of trying encoding a canvas as Base64 canvas.
  586. // e. Let encoded string be encoding result’s data.
  587. auto encoded_string = TRY(encode_bitmap_as_canvas_element(*screenshot.bitmap()));
  588. // 3. Return success with data encoded string.
  589. return JsonValue { encoded_string };
  590. }
  591. // 17.2 Take Element Screenshot, https://w3c.github.io/webdriver/#dfn-take-element-screenshot
  592. Web::WebDriver::Response Session::take_element_screenshot(StringView parameter_element_id)
  593. {
  594. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  595. TRY(check_for_open_top_level_browsing_context_or_return_error());
  596. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  597. // 3. Let element be the result of trying to get a known connected element with url variable element id.
  598. auto element_id = TRY(get_known_connected_element(parameter_element_id));
  599. // 4. Scroll into view the element.
  600. m_browser_connection->scroll_element_into_view(element_id);
  601. // 5. When the user agent is next to run the animation frame callbacks:
  602. // a. Let element rect be element’s rectangle.
  603. // b. Let screenshot result be the result of trying to call draw a bounding box from the framebuffer, given element rect as an argument.
  604. auto screenshot = m_browser_connection->take_element_screenshot(element_id);
  605. if (!screenshot.is_valid())
  606. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::UnableToCaptureScreen, "Unable to capture screenshot"sv);
  607. // c. Let canvas be a canvas element of screenshot result’s data.
  608. // d. Let encoding result be the result of trying encoding a canvas as Base64 canvas.
  609. // e. Let encoded string be encoding result’s data.
  610. auto encoded_string = TRY(encode_bitmap_as_canvas_element(*screenshot.bitmap()));
  611. // 6. Return success with data encoded string.
  612. return JsonValue { encoded_string };
  613. }
  614. }