Capabilities.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /*
  2. * Copyright (c) 2022, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/JsonArray.h>
  8. #include <AK/JsonObject.h>
  9. #include <AK/JsonValue.h>
  10. #include <AK/Optional.h>
  11. #include <LibWeb/Loader/UserAgent.h>
  12. #include <LibWeb/WebDriver/Capabilities.h>
  13. #include <LibWeb/WebDriver/TimeoutsConfiguration.h>
  14. namespace Web::WebDriver {
  15. // https://w3c.github.io/webdriver/#dfn-deserialize-as-a-page-load-strategy
  16. static Response deserialize_as_a_page_load_strategy(JsonValue value)
  17. {
  18. // 1. If value is not a string return an error with error code invalid argument.
  19. if (!value.is_string())
  20. return Error::from_code(ErrorCode::InvalidArgument, "Capability pageLoadStrategy must be a string"sv);
  21. // 2. If there is no entry in the table of page load strategies with keyword value return an error with error code invalid argument.
  22. if (!value.as_string().is_one_of("none"sv, "eager"sv, "normal"sv))
  23. return Error::from_code(ErrorCode::InvalidArgument, "Invalid pageLoadStrategy capability"sv);
  24. // 3. Return success with data value.
  25. return value;
  26. }
  27. // https://w3c.github.io/webdriver/#dfn-deserialize-as-an-unhandled-prompt-behavior
  28. static Response deserialize_as_an_unhandled_prompt_behavior(JsonValue value)
  29. {
  30. // 1. If value is not a string return an error with error code invalid argument.
  31. if (!value.is_string())
  32. return Error::from_code(ErrorCode::InvalidArgument, "Capability unhandledPromptBehavior must be a string"sv);
  33. // 2. If value is not present as a keyword in the known prompt handling approaches table return an error with error code invalid argument.
  34. if (!value.as_string().is_one_of("dismiss"sv, "accept"sv, "dismiss and notify"sv, "accept and notify"sv, "ignore"sv))
  35. return Error::from_code(ErrorCode::InvalidArgument, "Invalid pageLoadStrategy capability"sv);
  36. // 3. Return success with data value.
  37. return value;
  38. }
  39. // https://w3c.github.io/webdriver/#dfn-deserialize-as-a-proxy
  40. static ErrorOr<JsonObject, Error> deserialize_as_a_proxy(JsonValue parameter)
  41. {
  42. // 1. If parameter is not a JSON Object return an error with error code invalid argument.
  43. if (!parameter.is_object())
  44. return Error::from_code(ErrorCode::InvalidArgument, "Capability proxy must be an object"sv);
  45. // 2. Let proxy be a new, empty proxy configuration object.
  46. JsonObject proxy;
  47. // 3. For each enumerable own property in parameter run the following substeps:
  48. TRY(parameter.as_object().try_for_each_member([&](auto const& key, JsonValue const& value) -> ErrorOr<void, Error> {
  49. // 1. Let key be the name of the property.
  50. // 2. Let value be the result of getting a property named name from capability.
  51. // FIXME: 3. If there is no matching key for key in the proxy configuration table return an error with error code invalid argument.
  52. // FIXME: 4. If value is not one of the valid values for that key, return an error with error code invalid argument.
  53. // 5. Set a property key to value on proxy.
  54. proxy.set(key, value);
  55. return {};
  56. }));
  57. return proxy;
  58. }
  59. static Response deserialize_as_ladybird_options(JsonValue value)
  60. {
  61. if (!value.is_object())
  62. return Error::from_code(ErrorCode::InvalidArgument, "Extension capability serenity:ladybird must be an object"sv);
  63. auto const& object = value.as_object();
  64. if (auto headless = object.get("headless"sv); headless.has_value() && !headless->is_bool())
  65. return Error::from_code(ErrorCode::InvalidArgument, "Extension capability serenity:ladybird/headless must be a boolean"sv);
  66. return value;
  67. }
  68. static JsonObject default_ladybird_options()
  69. {
  70. JsonObject options;
  71. options.set("headless"sv, false);
  72. return options;
  73. }
  74. // https://w3c.github.io/webdriver/#dfn-validate-capabilities
  75. static ErrorOr<JsonObject, Error> validate_capabilities(JsonValue const& capability)
  76. {
  77. // 1. If capability is not a JSON Object return an error with error code invalid argument.
  78. if (!capability.is_object())
  79. return Error::from_code(ErrorCode::InvalidArgument, "Capability is not an Object"sv);
  80. // 2. Let result be an empty JSON Object.
  81. JsonObject result;
  82. // 3. For each enumerable own property in capability, run the following substeps:
  83. TRY(capability.as_object().try_for_each_member([&](auto const& name, JsonValue const& value) -> ErrorOr<void, Error> {
  84. // a. Let name be the name of the property.
  85. // b. Let value be the result of getting a property named name from capability.
  86. // c. Run the substeps of the first matching condition:
  87. JsonValue deserialized;
  88. // -> value is null
  89. if (value.is_null()) {
  90. // Let deserialized be set to null.
  91. }
  92. // -> name equals "acceptInsecureCerts"
  93. else if (name == "acceptInsecureCerts"sv) {
  94. // If value is not a boolean return an error with error code invalid argument. Otherwise, let deserialized be set to value
  95. if (!value.is_bool())
  96. return Error::from_code(ErrorCode::InvalidArgument, "Capability acceptInsecureCerts must be a boolean"sv);
  97. deserialized = value;
  98. }
  99. // -> name equals "browserName"
  100. // -> name equals "browserVersion"
  101. // -> name equals "platformName"
  102. else if (name.is_one_of("browserName"sv, "browserVersion"sv, "platformName"sv)) {
  103. // If value is not a string return an error with error code invalid argument. Otherwise, let deserialized be set to value.
  104. if (!value.is_string())
  105. return Error::from_code(ErrorCode::InvalidArgument, ByteString::formatted("Capability {} must be a string", name));
  106. deserialized = value;
  107. }
  108. // -> name equals "pageLoadStrategy"
  109. else if (name == "pageLoadStrategy"sv) {
  110. // Let deserialized be the result of trying to deserialize as a page load strategy with argument value.
  111. deserialized = TRY(deserialize_as_a_page_load_strategy(value));
  112. }
  113. // -> name equals "proxy"
  114. else if (name == "proxy"sv) {
  115. // Let deserialized be the result of trying to deserialize as a proxy with argument value.
  116. deserialized = TRY(deserialize_as_a_proxy(value));
  117. }
  118. // -> name equals "strictFileInteractability"
  119. else if (name == "strictFileInteractability"sv) {
  120. // If value is not a boolean return an error with error code invalid argument. Otherwise, let deserialized be set to value
  121. if (!value.is_bool())
  122. return Error::from_code(ErrorCode::InvalidArgument, "Capability strictFileInteractability must be a boolean"sv);
  123. deserialized = value;
  124. }
  125. // -> name equals "timeouts"
  126. else if (name == "timeouts"sv) {
  127. // Let deserialized be the result of trying to JSON deserialize as a timeouts configuration the value.
  128. auto timeouts = TRY(json_deserialize_as_a_timeouts_configuration(value));
  129. deserialized = JsonValue { timeouts_object(timeouts) };
  130. }
  131. // -> name equals "unhandledPromptBehavior"
  132. else if (name == "unhandledPromptBehavior"sv) {
  133. // Let deserialized be the result of trying to deserialize as an unhandled prompt behavior with argument value.
  134. deserialized = TRY(deserialize_as_an_unhandled_prompt_behavior(value));
  135. }
  136. // FIXME: -> name is the name of an additional WebDriver capability
  137. // FIXME: Let deserialized be the result of trying to run the additional capability deserialization algorithm for the extension capability corresponding to name, with argument value.
  138. // https://w3c.github.io/webdriver-bidi/#type-session-CapabilityRequest
  139. else if (name == "webSocketUrl"sv) {
  140. // 1. If value is not a boolean, return error with code invalid argument.
  141. if (!value.is_bool())
  142. return Error::from_code(ErrorCode::InvalidArgument, "Capability webSocketUrl must be a boolean"sv);
  143. // 2. Return success with data value.
  144. deserialized = value;
  145. }
  146. // -> name is the key of an extension capability
  147. // If name is known to the implementation, let deserialized be the result of trying to deserialize value in an implementation-specific way. Otherwise, let deserialized be set to value.
  148. else if (name == "serenity:ladybird"sv) {
  149. deserialized = TRY(deserialize_as_ladybird_options(value));
  150. }
  151. // -> The remote end is an endpoint node
  152. else {
  153. // Return an error with error code invalid argument.
  154. return Error::from_code(ErrorCode::InvalidArgument, ByteString::formatted("Unrecognized capability: {}", name));
  155. }
  156. // d. If deserialized is not null, set a property on result with name name and value deserialized.
  157. if (!deserialized.is_null())
  158. result.set(name, move(deserialized));
  159. return {};
  160. }));
  161. // 4. Return success with data result.
  162. return result;
  163. }
  164. // https://w3c.github.io/webdriver/#dfn-merging-capabilities
  165. static ErrorOr<JsonObject, Error> merge_capabilities(JsonObject const& primary, Optional<JsonObject const&> const& secondary)
  166. {
  167. // 1. Let result be a new JSON Object.
  168. JsonObject result;
  169. // 2. For each enumerable own property in primary, run the following substeps:
  170. primary.for_each_member([&](auto const& name, auto const& value) {
  171. // a. Let name be the name of the property.
  172. // b. Let value be the result of getting a property named name from primary.
  173. // c. Set a property on result with name name and value value.
  174. result.set(name, value);
  175. });
  176. // 3. If secondary is undefined, return result.
  177. if (!secondary.has_value())
  178. return result;
  179. // 4. For each enumerable own property in secondary, run the following substeps:
  180. TRY(secondary->try_for_each_member([&](auto const& name, auto const& value) -> ErrorOr<void, Error> {
  181. // a. Let name be the name of the property.
  182. // b. Let value be the result of getting a property named name from secondary.
  183. // c. Let primary value be the result of getting the property name from primary.
  184. auto primary_value = primary.get(name);
  185. // d. If primary value is not undefined, return an error with error code invalid argument.
  186. if (primary_value.has_value())
  187. return Error::from_code(ErrorCode::InvalidArgument, ByteString::formatted("Unable to merge capability {}", name));
  188. // e. Set a property on result with name name and value value.
  189. result.set(name, value);
  190. return {};
  191. }));
  192. // 5. Return result.
  193. return result;
  194. }
  195. static bool matches_browser_version(StringView requested_version, StringView required_version)
  196. {
  197. // FIXME: Handle relative (>, >=, <. <=) comparisons. For now, require an exact match.
  198. return requested_version == required_version;
  199. }
  200. static bool matches_platform_name(StringView requested_platform_name, StringView required_platform_name)
  201. {
  202. if (requested_platform_name == required_platform_name)
  203. return true;
  204. // The following platform names are in common usage with well-understood semantics and, when matching capabilities, greatest interoperability can be achieved by honoring them as valid synonyms for well-known Operating Systems:
  205. // "linux" Any server or desktop system based upon the Linux kernel.
  206. // "mac" Any version of Apple’s macOS.
  207. // "windows" Any version of Microsoft Windows, including desktop and mobile versions.
  208. // This list is not exhaustive.
  209. // NOTE: Of the synonyms listed in the spec, the only one that differs for us is macOS.
  210. // Further, we are allowed to handle synonyms for SerenityOS.
  211. if (requested_platform_name == "mac"sv && required_platform_name == "macos"sv)
  212. return true;
  213. if (requested_platform_name == "serenity"sv && required_platform_name == "serenityos"sv)
  214. return true;
  215. return false;
  216. }
  217. // https://w3c.github.io/webdriver/#dfn-matching-capabilities
  218. static JsonValue match_capabilities(JsonObject const& capabilities)
  219. {
  220. static auto browser_name = StringView { BROWSER_NAME, strlen(BROWSER_NAME) }.to_lowercase_string();
  221. static auto platform_name = StringView { OS_STRING, strlen(OS_STRING) }.to_lowercase_string();
  222. // 1. Let matched capabilities be a JSON Object with the following entries:
  223. JsonObject matched_capabilities;
  224. // "browserName"
  225. // ASCII Lowercase name of the user agent as a string.
  226. matched_capabilities.set("browserName"sv, browser_name);
  227. // "browserVersion"
  228. // The user agent version, as a string.
  229. matched_capabilities.set("browserVersion"sv, BROWSER_VERSION);
  230. // "platformName"
  231. // ASCII Lowercase name of the current platform as a string.
  232. matched_capabilities.set("platformName"sv, platform_name);
  233. // "acceptInsecureCerts"
  234. // Boolean initially set to false, indicating the session will not implicitly trust untrusted or self-signed TLS certificates on navigation.
  235. matched_capabilities.set("acceptInsecureCerts"sv, false);
  236. // "strictFileInteractability"
  237. // Boolean initially set to false, indicating that interactability checks will be applied to <input type=file>.
  238. matched_capabilities.set("strictFileInteractability"sv, false);
  239. // "setWindowRect"
  240. // Boolean indicating whether the remote end supports all of the resizing and positioning commands.
  241. matched_capabilities.set("setWindowRect"sv, true);
  242. // 2. Optionally add extension capabilities as entries to matched capabilities. The values of these may be elided, and there is no requirement that all extension capabilities be added.
  243. matched_capabilities.set("serenity:ladybird"sv, default_ladybird_options());
  244. // 3. For each name and value corresponding to capability’s own properties:
  245. auto result = capabilities.try_for_each_member([&](auto const& name, auto const& value) -> ErrorOr<void> {
  246. // a. Let match value equal value.
  247. // b. Run the substeps of the first matching name:
  248. // -> "browserName"
  249. if (name == "browserName"sv) {
  250. // If value is not a string equal to the "browserName" entry in matched capabilities, return success with data null.
  251. if (value.as_string() != matched_capabilities.get_byte_string(name).value())
  252. return AK::Error::from_string_literal("browserName");
  253. }
  254. // -> "browserVersion"
  255. else if (name == "browserVersion"sv) {
  256. // Compare value to the "browserVersion" entry in matched capabilities using an implementation-defined comparison algorithm. The comparison is to accept a value that places constraints on the version using the "<", "<=", ">", and ">=" operators.
  257. // If the two values do not match, return success with data null.
  258. if (!matches_browser_version(value.as_string(), matched_capabilities.get_byte_string(name).value()))
  259. return AK::Error::from_string_literal("browserVersion");
  260. }
  261. // -> "platformName"
  262. else if (name == "platformName"sv) {
  263. // If value is not a string equal to the "platformName" entry in matched capabilities, return success with data null.
  264. if (!matches_platform_name(value.as_string(), matched_capabilities.get_byte_string(name).value()))
  265. return AK::Error::from_string_literal("platformName");
  266. }
  267. // -> "acceptInsecureCerts"
  268. else if (name == "acceptInsecureCerts"sv) {
  269. // If value is true and the endpoint node does not support insecure TLS certificates, return success with data null.
  270. if (value.as_bool())
  271. return AK::Error::from_string_literal("acceptInsecureCerts");
  272. }
  273. // -> "proxy"
  274. else if (name == "proxy"sv) {
  275. // FIXME: If the endpoint node does not allow the proxy it uses to be configured, or if the proxy configuration defined in value is not one that passes the endpoint node’s implementation-specific validity checks, return success with data null.
  276. }
  277. // -> Otherwise
  278. else {
  279. // FIXME: If name is the name of an additional WebDriver capability which defines a matched capability serialization algorithm, let match value be the result of running the matched capability serialization algorithm for capability name with argument value.
  280. // FIXME: Otherwise, if name is the key of an extension capability, let match value be the result of trying implementation-specific steps to match on name with value. If the match is not successful, return success with data null.
  281. // https://w3c.github.io/webdriver-bidi/#type-session-CapabilityRequest
  282. if (name == "webSocketUrl"sv) {
  283. // 1. If value is false, return success with data null.
  284. if (!value.as_bool())
  285. return AK::Error::from_string_literal("webSocketUrl");
  286. // 2. Return success with data value.
  287. // FIXME: Remove this when we support BIDI communication.
  288. return AK::Error::from_string_literal("webSocketUrl");
  289. }
  290. }
  291. // c. Set a property on matched capabilities with name name and value match value.
  292. matched_capabilities.set(name, value);
  293. return {};
  294. });
  295. if (result.is_error()) {
  296. dbgln_if(WEBDRIVER_DEBUG, "Failed to match capability: {}", result.error());
  297. return JsonValue {};
  298. }
  299. // 4. Return success with data matched capabilities.
  300. return matched_capabilities;
  301. }
  302. // https://w3c.github.io/webdriver/#dfn-capabilities-processing
  303. Response process_capabilities(JsonValue const& parameters)
  304. {
  305. if (!parameters.is_object())
  306. return Error::from_code(ErrorCode::InvalidArgument, "Session parameters is not an object"sv);
  307. // 1. Let capabilities request be the result of getting the property "capabilities" from parameters.
  308. // a. If capabilities request is not a JSON Object, return error with error code invalid argument.
  309. auto maybe_capabilities_request = parameters.as_object().get_object("capabilities"sv);
  310. if (!maybe_capabilities_request.has_value())
  311. return Error::from_code(ErrorCode::InvalidArgument, "Capabilities is not an object"sv);
  312. auto const& capabilities_request = maybe_capabilities_request.value();
  313. // 2. Let required capabilities be the result of getting the property "alwaysMatch" from capabilities request.
  314. // a. If required capabilities is undefined, set the value to an empty JSON Object.
  315. JsonObject required_capabilities;
  316. if (auto capability = capabilities_request.get("alwaysMatch"sv); capability.has_value()) {
  317. // b. Let required capabilities be the result of trying to validate capabilities with argument required capabilities.
  318. required_capabilities = TRY(validate_capabilities(*capability));
  319. }
  320. // 3. Let all first match capabilities be the result of getting the property "firstMatch" from capabilities request.
  321. JsonArray all_first_match_capabilities;
  322. if (auto capabilities = capabilities_request.get("firstMatch"sv); capabilities.has_value()) {
  323. // b. If all first match capabilities is not a JSON List with one or more entries, return error with error code invalid argument.
  324. if (!capabilities->is_array() || capabilities->as_array().is_empty())
  325. return Error::from_code(ErrorCode::InvalidArgument, "Capability firstMatch must be an array with at least one entry"sv);
  326. all_first_match_capabilities = capabilities->as_array();
  327. } else {
  328. // a. If all first match capabilities is undefined, set the value to a JSON List with a single entry of an empty JSON Object.
  329. all_first_match_capabilities.must_append(JsonObject {});
  330. }
  331. // 4. Let validated first match capabilities be an empty JSON List.
  332. JsonArray validated_first_match_capabilities;
  333. validated_first_match_capabilities.ensure_capacity(all_first_match_capabilities.size());
  334. // 5. For each first match capabilities corresponding to an indexed property in all first match capabilities:
  335. TRY(all_first_match_capabilities.try_for_each([&](auto const& first_match_capabilities) -> ErrorOr<void, Error> {
  336. // a. Let validated capabilities be the result of trying to validate capabilities with argument first match capabilities.
  337. auto validated_capabilities = TRY(validate_capabilities(first_match_capabilities));
  338. // b. Append validated capabilities to validated first match capabilities.
  339. validated_first_match_capabilities.must_append(move(validated_capabilities));
  340. return {};
  341. }));
  342. // 6. Let merged capabilities be an empty List.
  343. JsonArray merged_capabilities;
  344. merged_capabilities.ensure_capacity(validated_first_match_capabilities.size());
  345. // 7. For each first match capabilities corresponding to an indexed property in validated first match capabilities:
  346. TRY(validated_first_match_capabilities.try_for_each([&](auto const& first_match_capabilities) -> ErrorOr<void, Error> {
  347. // a. Let merged be the result of trying to merge capabilities with required capabilities and first match capabilities as arguments.
  348. auto merged = TRY(merge_capabilities(required_capabilities, first_match_capabilities.as_object()));
  349. // b. Append merged to merged capabilities.
  350. merged_capabilities.must_append(move(merged));
  351. return {};
  352. }));
  353. // 8. For each capabilities corresponding to an indexed property in merged capabilities:
  354. for (auto const& capabilities : merged_capabilities.values()) {
  355. // a. Let matched capabilities be the result of trying to match capabilities with capabilities as an argument.
  356. auto matched_capabilities = match_capabilities(capabilities.as_object());
  357. // b. If matched capabilities is not null, return success with data matched capabilities.
  358. if (!matched_capabilities.is_null())
  359. return matched_capabilities;
  360. }
  361. // 9. Return success with data null.
  362. return JsonValue {};
  363. }
  364. LadybirdOptions::LadybirdOptions(JsonObject const& capabilities)
  365. {
  366. auto options = capabilities.get_object("serenity:ladybird"sv);
  367. if (!options.has_value())
  368. return;
  369. auto headless = options->get_bool("headless"sv);
  370. if (headless.has_value())
  371. this->headless = headless.value();
  372. }
  373. }