Session.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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/NumericLimits.h>
  14. #include <AK/Time.h>
  15. #include <LibCore/LocalServer.h>
  16. #include <LibCore/Stream.h>
  17. #include <LibCore/System.h>
  18. #include <LibGfx/Point.h>
  19. #include <LibGfx/Rect.h>
  20. #include <LibGfx/Size.h>
  21. #include <LibWeb/Cookie/Cookie.h>
  22. #include <LibWeb/Cookie/ParsedCookie.h>
  23. #include <LibWeb/WebDriver/ExecuteScript.h>
  24. #include <unistd.h>
  25. namespace WebDriver {
  26. Session::Session(unsigned session_id, NonnullRefPtr<Client> client)
  27. : m_client(move(client))
  28. , m_id(session_id)
  29. {
  30. }
  31. Session::~Session()
  32. {
  33. if (m_started) {
  34. auto error = stop();
  35. if (error.is_error()) {
  36. warnln("Failed to stop session {}: {}", m_id, error.error());
  37. }
  38. }
  39. }
  40. ErrorOr<Session::Window*, Web::WebDriver::Error> Session::current_window()
  41. {
  42. auto window = m_windows.get(m_current_window_handle);
  43. if (!window.has_value())
  44. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchWindow, "Window not found");
  45. return window.release_value();
  46. }
  47. ErrorOr<void, Web::WebDriver::Error> Session::check_for_open_top_level_browsing_context_or_return_error()
  48. {
  49. (void)TRY(current_window());
  50. return {};
  51. }
  52. ErrorOr<NonnullRefPtr<Core::LocalServer>> Session::create_server(String const& socket_path, ServerType type, NonnullRefPtr<ServerPromise> promise)
  53. {
  54. dbgln("Listening for WebDriver connection on {}", socket_path);
  55. auto server = TRY(Core::LocalServer::try_create());
  56. server->listen(socket_path);
  57. server->on_accept = [this, type, promise](auto client_socket) mutable {
  58. switch (type) {
  59. case ServerType::Browser: {
  60. auto maybe_connection = adopt_nonnull_ref_or_enomem(new (nothrow) BrowserConnection(move(client_socket), m_client, session_id()));
  61. if (maybe_connection.is_error()) {
  62. promise->resolve(maybe_connection.release_error());
  63. return;
  64. }
  65. dbgln("WebDriver is connected to Browser socket");
  66. m_browser_connection = maybe_connection.release_value();
  67. break;
  68. }
  69. case ServerType::WebContent: {
  70. auto maybe_connection = adopt_nonnull_ref_or_enomem(new (nothrow) WebContentConnection(move(client_socket), m_client, session_id()));
  71. if (maybe_connection.is_error()) {
  72. promise->resolve(maybe_connection.release_error());
  73. return;
  74. }
  75. dbgln("WebDriver is connected to WebContent socket");
  76. m_web_content_connection = maybe_connection.release_value();
  77. break;
  78. }
  79. }
  80. if (m_browser_connection && m_web_content_connection)
  81. promise->resolve({});
  82. };
  83. server->on_accept_error = [promise](auto error) mutable {
  84. promise->resolve(move(error));
  85. };
  86. return server;
  87. }
  88. ErrorOr<void> Session::start()
  89. {
  90. auto promise = TRY(ServerPromise::try_create());
  91. auto browser_socket_path = String::formatted("/tmp/webdriver/browser_{}_{}", getpid(), m_id);
  92. auto browser_server = TRY(create_server(browser_socket_path, ServerType::Browser, promise));
  93. auto web_content_socket_path = String::formatted("/tmp/webdriver/content_{}_{}", getpid(), m_id);
  94. auto web_content_server = TRY(create_server(web_content_socket_path, ServerType::WebContent, promise));
  95. char const* argv[] = {
  96. "/bin/Browser",
  97. "--webdriver-browser-path",
  98. browser_socket_path.characters(),
  99. "--webdriver-content-path",
  100. web_content_socket_path.characters(),
  101. nullptr,
  102. };
  103. TRY(Core::System::posix_spawn("/bin/Browser"sv, nullptr, nullptr, const_cast<char**>(argv), environ));
  104. // FIXME: Allow this to be more asynchronous. For now, this at least allows us to propagate
  105. // errors received while accepting the Browser and WebContent sockets.
  106. TRY(promise->await());
  107. m_started = true;
  108. m_windows.set("main", make<Session::Window>("main", true));
  109. m_current_window_handle = "main";
  110. return {};
  111. }
  112. // https://w3c.github.io/webdriver/#dfn-close-the-session
  113. Web::WebDriver::Response Session::stop()
  114. {
  115. // 1. Perform the following substeps based on the remote end’s type:
  116. // NOTE: We perform the "Remote end is an endpoint node" steps in the WebContent process.
  117. m_web_content_connection->close_session();
  118. m_web_content_connection = nullptr;
  119. // 2. Remove the current session from active sessions.
  120. // NOTE: Handled by WebDriver::Client.
  121. // 3. Perform any implementation-specific cleanup steps.
  122. m_browser_connection->async_quit();
  123. m_started = false;
  124. // 4. If an error has occurred in any of the steps above, return the error, otherwise return success with data null.
  125. return JsonValue {};
  126. }
  127. // 9.1 Get Timeouts, https://w3c.github.io/webdriver/#dfn-get-timeouts
  128. JsonObject Session::get_timeouts()
  129. {
  130. // 1. Let timeouts be the timeouts object for session’s timeouts configuration
  131. auto timeouts = timeouts_object(m_timeouts_configuration);
  132. // 2. Return success with data timeouts.
  133. return timeouts;
  134. }
  135. // 9.2 Set Timeouts, https://w3c.github.io/webdriver/#dfn-set-timeouts
  136. Web::WebDriver::Response Session::set_timeouts(JsonValue const& payload)
  137. {
  138. // 1. Let timeouts be the result of trying to JSON deserialize as a timeouts configuration the request’s parameters.
  139. auto timeouts = TRY(json_deserialize_as_a_timeouts_configuration(payload));
  140. // 2. Make the session timeouts the new timeouts.
  141. m_timeouts_configuration = move(timeouts);
  142. // 3. Return success with data null.
  143. return JsonValue {};
  144. }
  145. // 10.3 Back, https://w3c.github.io/webdriver/#dfn-back
  146. Web::WebDriver::Response Session::back()
  147. {
  148. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  149. TRY(check_for_open_top_level_browsing_context_or_return_error());
  150. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  151. // 3. Traverse the history by a delta –1 for the current browsing context.
  152. m_browser_connection->async_back();
  153. // FIXME: 4. If the previous step completed results in a pageHide event firing, wait until pageShow event
  154. // fires or for the session page load timeout milliseconds to pass, whichever occurs sooner.
  155. // FIXME: 5. If the previous step completed by the session page load timeout being reached, and user
  156. // prompts have been handled, return error with error code timeout.
  157. // 6. Return success with data null.
  158. return JsonValue();
  159. }
  160. // 10.4 Forward, https://w3c.github.io/webdriver/#dfn-forward
  161. Web::WebDriver::Response Session::forward()
  162. {
  163. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  164. TRY(check_for_open_top_level_browsing_context_or_return_error());
  165. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  166. // 3. Traverse the history by a delta 1 for the current browsing context.
  167. m_browser_connection->async_forward();
  168. // FIXME: 4. If the previous step completed results in a pageHide event firing, wait until pageShow event
  169. // fires or for the session page load timeout milliseconds to pass, whichever occurs sooner.
  170. // FIXME: 5. If the previous step completed by the session page load timeout being reached, and user
  171. // prompts have been handled, return error with error code timeout.
  172. // 6. Return success with data null.
  173. return JsonValue();
  174. }
  175. // 10.5 Refresh, https://w3c.github.io/webdriver/#dfn-refresh
  176. Web::WebDriver::Response Session::refresh()
  177. {
  178. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  179. TRY(check_for_open_top_level_browsing_context_or_return_error());
  180. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  181. // 3. Initiate an overridden reload of the current top-level browsing context’s active document.
  182. m_browser_connection->async_refresh();
  183. // FIXME: 4. If url is special except for file:
  184. // FIXME: 1. Try to wait for navigation to complete.
  185. // FIXME: 2. Try to run the post-navigation checks.
  186. // FIXME: 5. Set the current browsing context with current top-level browsing context.
  187. // 6. Return success with data null.
  188. return JsonValue();
  189. }
  190. // 10.6 Get Title, https://w3c.github.io/webdriver/#dfn-get-title
  191. Web::WebDriver::Response Session::get_title()
  192. {
  193. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  194. TRY(check_for_open_top_level_browsing_context_or_return_error());
  195. // FIXME: 2. Handle any user prompts and return its value if it is an error.
  196. // 3. Let title be the initial value of the title IDL attribute of the current top-level browsing context's active document.
  197. // 4. Return success with data title.
  198. return JsonValue(m_browser_connection->get_title());
  199. }
  200. // 11.1 Get Window Handle, https://w3c.github.io/webdriver/#get-window-handle
  201. Web::WebDriver::Response Session::get_window_handle()
  202. {
  203. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  204. TRY(check_for_open_top_level_browsing_context_or_return_error());
  205. // 2. Return success with data being the window handle associated with the current top-level browsing context.
  206. return JsonValue { m_current_window_handle };
  207. }
  208. // 11.2 Close Window, https://w3c.github.io/webdriver/#dfn-close-window
  209. ErrorOr<void, Variant<Web::WebDriver::Error, Error>> Session::close_window()
  210. {
  211. // 1. If the current top-level browsing context is no longer open, return error with error code no such window.
  212. TRY(check_for_open_top_level_browsing_context_or_return_error());
  213. // 2. Close the current top-level browsing context.
  214. m_windows.remove(m_current_window_handle);
  215. // 3. If there are no more open top-level browsing contexts, then close the session.
  216. if (m_windows.is_empty()) {
  217. auto result = stop();
  218. if (result.is_error()) {
  219. return Variant<Web::WebDriver::Error, Error>(result.release_error());
  220. }
  221. }
  222. return {};
  223. }
  224. // 11.4 Get Window Handles, https://w3c.github.io/webdriver/#dfn-get-window-handles
  225. Web::WebDriver::Response Session::get_window_handles() const
  226. {
  227. // 1. Let handles be a JSON List.
  228. auto handles = JsonArray {};
  229. // 2. For each top-level browsing context in the remote end, push the associated window handle onto handles.
  230. for (auto const& window_handle : m_windows.keys())
  231. handles.append(window_handle);
  232. // 3. Return success with data handles.
  233. return JsonValue { handles };
  234. }
  235. struct ScriptArguments {
  236. String script;
  237. JsonArray const& arguments;
  238. };
  239. // https://w3c.github.io/webdriver/#dfn-extract-the-script-arguments-from-a-request
  240. static ErrorOr<ScriptArguments, Web::WebDriver::Error> extract_the_script_arguments_from_a_request(JsonValue const& payload)
  241. {
  242. if (!payload.is_object())
  243. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload is not a JSON object");
  244. auto const& properties = payload.as_object();
  245. // 1. Let script be the result of getting a property named script from the parameters.
  246. // 2. If script is not a String, return error with error code invalid argument.
  247. if (!properties.has_string("script"sv))
  248. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have a 'script' string property");
  249. auto script = properties.get("script"sv).as_string();
  250. // 3. Let args be the result of getting a property named args from the parameters.
  251. // 4. If args is not an Array return error with error code invalid argument.
  252. if (!properties.has_array("args"sv))
  253. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have an 'args' string property");
  254. auto const& args = properties.get("args"sv).as_array();
  255. // 5. Let arguments be the result of calling the JSON deserialize algorithm with arguments args.
  256. // NOTE: We forward the JSON array to the Browser and then WebContent process over IPC, so this is not necessary.
  257. // 6. Return success with data script and arguments.
  258. return ScriptArguments { script, args };
  259. }
  260. // 13.2.1 Execute Script, https://w3c.github.io/webdriver/#dfn-execute-script
  261. Web::WebDriver::Response Session::execute_script(JsonValue const& payload)
  262. {
  263. // 1. Let body and arguments be the result of trying to extract the script arguments from a request with argument parameters.
  264. auto const& [body, arguments] = TRY(extract_the_script_arguments_from_a_request(payload));
  265. // 2. If the current browsing context is no longer open, return error with error code no such window.
  266. TRY(check_for_open_top_level_browsing_context_or_return_error());
  267. // FIXME: 3. Handle any user prompts, and return its value if it is an error.
  268. // 4., 5.1-5.3.
  269. Vector<String> json_arguments;
  270. arguments.for_each([&](JsonValue const& json_value) {
  271. // NOTE: serialized() instead of to_string() ensures proper quoting.
  272. json_arguments.append(json_value.serialized<StringBuilder>());
  273. });
  274. dbgln("Executing script with 'args': [{}] / 'body':\n{}", String::join(", "sv, json_arguments), body);
  275. auto execute_script_response = m_browser_connection->execute_script(body, json_arguments, m_timeouts_configuration.script_timeout, false);
  276. dbgln("Executing script returned: {}", execute_script_response.json_result());
  277. // NOTE: This is assumed to be a valid JSON value.
  278. auto result = MUST(JsonValue::from_string(execute_script_response.json_result()));
  279. switch (execute_script_response.result_type()) {
  280. // 6. If promise is still pending and the session script timeout is reached, return error with error code script timeout.
  281. case Web::WebDriver::ExecuteScriptResultType::Timeout:
  282. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::ScriptTimeoutError, "Script timed out");
  283. // 7. Upon fulfillment of promise with value v, let result be a JSON clone of v, and return success with data result.
  284. case Web::WebDriver::ExecuteScriptResultType::PromiseResolved:
  285. return result;
  286. // 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.
  287. case Web::WebDriver::ExecuteScriptResultType::PromiseRejected:
  288. case Web::WebDriver::ExecuteScriptResultType::JavaScriptError:
  289. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::JavascriptError, "Script returned an error", move(result));
  290. default:
  291. VERIFY_NOT_REACHED();
  292. }
  293. }
  294. // 13.2.2 Execute Async Script, https://w3c.github.io/webdriver/#dfn-execute-async-script
  295. Web::WebDriver::Response Session::execute_async_script(JsonValue const& parameters)
  296. {
  297. // 1. Let body and arguments by the result of trying to extract the script arguments from a request with argument parameters.
  298. auto [body, arguments] = TRY(extract_the_script_arguments_from_a_request(parameters));
  299. // 2. If the current browsing context is no longer open, return error with error code no such window.
  300. TRY(check_for_open_top_level_browsing_context_or_return_error());
  301. // FIXME: 3. Handle any user prompts, and return its value if it is an error.
  302. // 4., 5.1-5.11.
  303. Vector<String> json_arguments;
  304. arguments.for_each([&](JsonValue const& json_value) {
  305. // NOTE: serialized() instead of to_string() ensures proper quoting.
  306. json_arguments.append(json_value.serialized<StringBuilder>());
  307. });
  308. dbgln("Executing async script with 'args': [{}] / 'body':\n{}", String::join(", "sv, json_arguments), body);
  309. auto execute_script_response = m_browser_connection->execute_script(body, json_arguments, m_timeouts_configuration.script_timeout, true);
  310. dbgln("Executing async script returned: {}", execute_script_response.json_result());
  311. // NOTE: This is assumed to be a valid JSON value.
  312. auto result = MUST(JsonValue::from_string(execute_script_response.json_result()));
  313. switch (execute_script_response.result_type()) {
  314. // 6. If promise is still pending and the session script timeout is reached, return error with error code script timeout.
  315. case Web::WebDriver::ExecuteScriptResultType::Timeout:
  316. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::ScriptTimeoutError, "Script timed out");
  317. // 7. Upon fulfillment of promise with value v, let result be a JSON clone of v, and return success with data result.
  318. case Web::WebDriver::ExecuteScriptResultType::PromiseResolved:
  319. return result;
  320. // 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.
  321. case Web::WebDriver::ExecuteScriptResultType::PromiseRejected:
  322. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::JavascriptError, "Script returned an error", move(result));
  323. default:
  324. VERIFY_NOT_REACHED();
  325. }
  326. }
  327. // https://w3c.github.io/webdriver/#dfn-serialized-cookie
  328. static JsonObject serialize_cookie(Web::Cookie::Cookie const& cookie)
  329. {
  330. JsonObject serialized_cookie = {};
  331. serialized_cookie.set("name", cookie.name);
  332. serialized_cookie.set("value", cookie.value);
  333. serialized_cookie.set("path", cookie.path);
  334. serialized_cookie.set("domain", cookie.domain);
  335. serialized_cookie.set("secure", cookie.secure);
  336. serialized_cookie.set("httpOnly", cookie.http_only);
  337. serialized_cookie.set("expiry", cookie.expiry_time.timestamp());
  338. // FIXME: Add sameSite to Cookie and serialize it here too.
  339. return serialized_cookie;
  340. }
  341. // 14.1 Get All Cookies, https://w3c.github.io/webdriver/#dfn-get-all-cookies
  342. Web::WebDriver::Response Session::get_all_cookies()
  343. {
  344. // 1. If the current browsing context is no longer open, return error with error code no such window.
  345. TRY(check_for_open_top_level_browsing_context_or_return_error());
  346. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  347. // 3. Let cookies be a new JSON List.
  348. JsonArray cookies = {};
  349. // 4. For each cookie in all associated cookies of the current browsing context’s active document:
  350. for (auto const& cookie : m_browser_connection->get_all_cookies()) {
  351. // 1. Let serialized cookie be the result of serializing cookie.
  352. auto serialized_cookie = serialize_cookie(cookie);
  353. // 2. Append serialized cookie to cookies
  354. cookies.append(serialized_cookie);
  355. }
  356. // 5. Return success with data cookies.
  357. return JsonValue(cookies);
  358. }
  359. // 14.2 Get Named Cookie, https://w3c.github.io/webdriver/#dfn-get-named-cookie
  360. Web::WebDriver::Response Session::get_named_cookie(String const& name)
  361. {
  362. // 1. If the current browsing context is no longer open, return error with error code no such window.
  363. TRY(check_for_open_top_level_browsing_context_or_return_error());
  364. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  365. // 3. If the url variable name is equal to a cookie’s cookie name amongst all associated cookies of the
  366. // current browsing context’s active document, return success with the serialized cookie as data.
  367. auto maybe_cookie = m_browser_connection->get_named_cookie(name);
  368. if (maybe_cookie.has_value()) {
  369. auto cookie = maybe_cookie.release_value();
  370. auto serialized_cookie = serialize_cookie(cookie);
  371. return JsonValue(serialized_cookie);
  372. }
  373. // 4. Otherwise, return error with error code no such cookie.
  374. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::NoSuchCookie, "Cookie not found");
  375. }
  376. // 14.3 Add Cookie, https://w3c.github.io/webdriver/#dfn-adding-a-cookie
  377. Web::WebDriver::Response Session::add_cookie(JsonValue const& payload)
  378. {
  379. // 1. Let data be the result of getting a property named cookie from the parameters argument.
  380. if (!payload.is_object() || !payload.as_object().has_object("cookie"sv))
  381. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Payload doesn't have a cookie object");
  382. auto const& maybe_data = payload.as_object().get("cookie"sv);
  383. // 2. If data is not a JSON Object with all the required (non-optional) JSON keys listed in the table for cookie conversion,
  384. // return error with error code invalid argument.
  385. // NOTE: Table is here: https://w3c.github.io/webdriver/#dfn-table-for-cookie-conversion
  386. if (!maybe_data.is_object())
  387. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Value \"cookie\' is not an object");
  388. auto const& data = maybe_data.as_object();
  389. if (!data.has("name"sv) || !data.has("value"sv))
  390. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object doesn't contain all required keys");
  391. // 3. If the current browsing context is no longer open, return error with error code no such window.
  392. TRY(check_for_open_top_level_browsing_context_or_return_error());
  393. // FIXME: 4. Handle any user prompts, and return its value if it is an error.
  394. // FIXME: 5. If the current browsing context’s document element is a cookie-averse Document object,
  395. // return error with error code invalid cookie domain.
  396. // 6. If cookie name or cookie value is null,
  397. // FIXME: cookie domain is not equal to the current browsing context’s active document’s domain,
  398. // cookie secure only or cookie HTTP only are not boolean types,
  399. // or cookie expiry time is not an integer type, or it less than 0 or greater than the maximum safe integer,
  400. // return error with error code invalid argument.
  401. if (data.get("name"sv).is_null() || data.get("value"sv).is_null())
  402. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: name or value are null");
  403. if (data.has("secure"sv) && !data.get("secure"sv).is_bool())
  404. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: secure is not bool");
  405. if (data.has("httpOnly"sv) && !data.get("httpOnly"sv).is_bool())
  406. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: httpOnly is not bool");
  407. Optional<Core::DateTime> expiry_time;
  408. if (data.has("expiry"sv)) {
  409. auto expiry_argument = data.get("expiry"sv);
  410. if (!expiry_argument.is_u32()) {
  411. // NOTE: less than 0 or greater than safe integer are handled by the JSON parser
  412. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Cookie-Object is malformed: expiry is not u32");
  413. }
  414. expiry_time = Core::DateTime::from_timestamp(expiry_argument.as_u32());
  415. }
  416. // 7. Create a cookie in the cookie store associated with the active document’s address using
  417. // cookie name name, cookie value value, and an attribute-value list of the following cookie concepts
  418. // listed in the table for cookie conversion from data:
  419. Web::Cookie::ParsedCookie cookie;
  420. if (auto name_attribute = data.get("name"sv); name_attribute.is_string())
  421. cookie.name = name_attribute.as_string();
  422. else
  423. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect name attribute to be string");
  424. if (auto value_attribute = data.get("value"sv); value_attribute.is_string())
  425. cookie.value = value_attribute.as_string();
  426. else
  427. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect value attribute to be string");
  428. // Cookie path
  429. // The value if the entry exists, otherwise "/".
  430. if (data.has("path"sv)) {
  431. if (auto path_attribute = data.get("path"sv); path_attribute.is_string())
  432. cookie.path = path_attribute.as_string();
  433. else
  434. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect path attribute to be string");
  435. } else {
  436. cookie.path = "/";
  437. }
  438. // Cookie domain
  439. // The value if the entry exists, otherwise the current browsing context’s active document’s URL domain.
  440. // NOTE: The otherwise case is handled by the CookieJar
  441. if (data.has("domain"sv)) {
  442. if (auto domain_attribute = data.get("domain"sv); domain_attribute.is_string())
  443. cookie.domain = domain_attribute.as_string();
  444. else
  445. return Web::WebDriver::Error::from_code(Web::WebDriver::ErrorCode::InvalidArgument, "Expect domain attribute to be string");
  446. }
  447. // Cookie secure only
  448. // The value if the entry exists, otherwise false.
  449. if (data.has("secure"sv)) {
  450. cookie.secure_attribute_present = data.get("secure"sv).as_bool();
  451. } else {
  452. cookie.secure_attribute_present = false;
  453. }
  454. // Cookie HTTP only
  455. // The value if the entry exists, otherwise false.
  456. if (data.has("httpOnly"sv)) {
  457. cookie.http_only_attribute_present = data.get("httpOnly"sv).as_bool();
  458. } else {
  459. cookie.http_only_attribute_present = false;
  460. }
  461. // Cookie expiry time
  462. // The value if the entry exists, otherwise leave unset to indicate that this is a session cookie.
  463. cookie.expiry_time_from_expires_attribute = expiry_time;
  464. // FIXME: Cookie same site
  465. // The value if the entry exists, otherwise leave unset to indicate that no same site policy is defined.
  466. m_browser_connection->async_add_cookie(move(cookie));
  467. // If there is an error during this step, return error with error code unable to set cookie.
  468. // NOTE: This probably should only apply to the actual setting of the cookie in the Browser,
  469. // which cannot fail in our case.
  470. // Thus, the error-codes used above are 400 "invalid argument".
  471. // 8. Return success with data null.
  472. return JsonValue();
  473. }
  474. // https://w3c.github.io/webdriver/#dfn-delete-cookies
  475. void Session::delete_cookies(Optional<StringView> const& name)
  476. {
  477. // For each cookie among all associated cookies of the current browsing context’s active document,
  478. // run the substeps of the first matching condition:
  479. for (auto& cookie : m_browser_connection->get_all_cookies()) {
  480. // -> name is undefined
  481. // -> name is equal to cookie name
  482. if (!name.has_value() || name.value() == cookie.name) {
  483. // Set the cookie expiry time to a Unix timestamp in the past.
  484. cookie.expiry_time = Core::DateTime::from_timestamp(0);
  485. m_browser_connection->async_update_cookie(cookie);
  486. }
  487. // -> Otherwise
  488. // Do nothing.
  489. }
  490. }
  491. // 14.4 Delete Cookie, https://w3c.github.io/webdriver/#dfn-delete-cookie
  492. Web::WebDriver::Response Session::delete_cookie(StringView name)
  493. {
  494. // 1. If the current browsing context is no longer open, return error with error code no such window.
  495. TRY(check_for_open_top_level_browsing_context_or_return_error());
  496. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  497. // 3. Delete cookies using the url variable name parameter as the filter argument.
  498. delete_cookies(name);
  499. // 4. Return success with data null.
  500. return JsonValue();
  501. }
  502. // 14.5 Delete All Cookies, https://w3c.github.io/webdriver/#dfn-delete-all-cookies
  503. Web::WebDriver::Response Session::delete_all_cookies()
  504. {
  505. // 1. If the current browsing context is no longer open, return error with error code no such window.
  506. TRY(check_for_open_top_level_browsing_context_or_return_error());
  507. // FIXME: 2. Handle any user prompts, and return its value if it is an error.
  508. // 3. Delete cookies, giving no filtering argument.
  509. delete_cookies();
  510. // 4. Return success with data null.
  511. return JsonValue();
  512. }
  513. }