Capabilities.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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/ResourceLoader.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. static Response deserialize_as_ladybird_options(JsonValue value)
  40. {
  41. if (!value.is_object())
  42. return Error::from_code(ErrorCode::InvalidArgument, "Extension capability serenity:ladybird must be an object"sv);
  43. auto const& object = value.as_object();
  44. if (auto headless = object.get("headless"sv); headless.has_value() && !headless->is_bool())
  45. return Error::from_code(ErrorCode::InvalidArgument, "Extension capability serenity:ladybird/headless must be a boolean"sv);
  46. return value;
  47. }
  48. static JsonObject default_ladybird_options()
  49. {
  50. JsonObject options;
  51. options.set("headless"sv, false);
  52. return options;
  53. }
  54. // https://w3c.github.io/webdriver/#dfn-validate-capabilities
  55. static ErrorOr<JsonObject, Error> validate_capabilities(JsonValue const& capability)
  56. {
  57. // 1. If capability is not a JSON Object return an error with error code invalid argument.
  58. if (!capability.is_object())
  59. return Error::from_code(ErrorCode::InvalidArgument, "Capability is not an Object"sv);
  60. // 2. Let result be an empty JSON Object.
  61. JsonObject result;
  62. // 3. For each enumerable own property in capability, run the following substeps:
  63. TRY(capability.as_object().try_for_each_member([&](auto const& name, auto const& value) -> ErrorOr<void, Error> {
  64. // a. Let name be the name of the property.
  65. // b. Let value be the result of getting a property named name from capability.
  66. // c. Run the substeps of the first matching condition:
  67. JsonValue deserialized;
  68. // -> value is null
  69. if (value.is_null()) {
  70. // Let deserialized be set to null.
  71. }
  72. // -> name equals "acceptInsecureCerts"
  73. else if (name == "acceptInsecureCerts"sv) {
  74. // If value is not a boolean return an error with error code invalid argument. Otherwise, let deserialized be set to value
  75. if (!value.is_bool())
  76. return Error::from_code(ErrorCode::InvalidArgument, "Capability acceptInsecureCerts must be a boolean"sv);
  77. deserialized = value;
  78. }
  79. // -> name equals "browserName"
  80. // -> name equals "browserVersion"
  81. // -> name equals "platformName"
  82. else if (name.is_one_of("browserName"sv, "browserVersion"sv, "platformName"sv)) {
  83. // If value is not a string return an error with error code invalid argument. Otherwise, let deserialized be set to value.
  84. if (!value.is_string())
  85. return Error::from_code(ErrorCode::InvalidArgument, DeprecatedString::formatted("Capability {} must be a string", name));
  86. deserialized = value;
  87. }
  88. // -> name equals "pageLoadStrategy"
  89. else if (name == "pageLoadStrategy"sv) {
  90. // Let deserialized be the result of trying to deserialize as a page load strategy with argument value.
  91. deserialized = TRY(deserialize_as_a_page_load_strategy(value));
  92. }
  93. // FIXME: -> name equals "proxy"
  94. // FIXME: Let deserialized be the result of trying to deserialize as a proxy with argument value.
  95. // -> name equals "strictFileInteractability"
  96. else if (name == "strictFileInteractability"sv) {
  97. // If value is not a boolean return an error with error code invalid argument. Otherwise, let deserialized be set to value
  98. if (!value.is_bool())
  99. return Error::from_code(ErrorCode::InvalidArgument, "Capability strictFileInteractability must be a boolean"sv);
  100. deserialized = value;
  101. }
  102. // -> name equals "timeouts"
  103. else if (name == "timeouts"sv) {
  104. // Let deserialized be the result of trying to JSON deserialize as a timeouts configuration the value.
  105. auto timeouts = TRY(json_deserialize_as_a_timeouts_configuration(value));
  106. deserialized = JsonValue { timeouts_object(timeouts) };
  107. }
  108. // -> name equals "unhandledPromptBehavior"
  109. else if (name == "unhandledPromptBehavior"sv) {
  110. // Let deserialized be the result of trying to deserialize as an unhandled prompt behavior with argument value.
  111. deserialized = TRY(deserialize_as_an_unhandled_prompt_behavior(value));
  112. }
  113. // FIXME: -> name is the name of an additional WebDriver capability
  114. // 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.
  115. // -> name is the key of an extension capability
  116. // 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.
  117. else if (name == "serenity:ladybird"sv) {
  118. deserialized = TRY(deserialize_as_ladybird_options(value));
  119. }
  120. // -> The remote end is an endpoint node
  121. else {
  122. // Return an error with error code invalid argument.
  123. return Error::from_code(ErrorCode::InvalidArgument, DeprecatedString::formatted("Unrecognized capability: {}", name));
  124. }
  125. // d. If deserialized is not null, set a property on result with name name and value deserialized.
  126. if (!deserialized.is_null())
  127. result.set(name, move(deserialized));
  128. return {};
  129. }));
  130. // 4. Return success with data result.
  131. return result;
  132. }
  133. // https://w3c.github.io/webdriver/#dfn-merging-capabilities
  134. static ErrorOr<JsonObject, Error> merge_capabilities(JsonObject const& primary, Optional<JsonObject const&> const& secondary)
  135. {
  136. // 1. Let result be a new JSON Object.
  137. JsonObject result;
  138. // 2. For each enumerable own property in primary, run the following substeps:
  139. primary.for_each_member([&](auto const& name, auto const& value) {
  140. // a. Let name be the name of the property.
  141. // b. Let value be the result of getting a property named name from primary.
  142. // c. Set a property on result with name name and value value.
  143. result.set(name, value);
  144. });
  145. // 3. If secondary is undefined, return result.
  146. if (!secondary.has_value())
  147. return result;
  148. // 4. For each enumerable own property in secondary, run the following substeps:
  149. TRY(secondary->try_for_each_member([&](auto const& name, auto const& value) -> ErrorOr<void, Error> {
  150. // a. Let name be the name of the property.
  151. // b. Let value be the result of getting a property named name from secondary.
  152. // c. Let primary value be the result of getting the property name from primary.
  153. auto primary_value = primary.get(name);
  154. // d. If primary value is not undefined, return an error with error code invalid argument.
  155. if (primary_value.has_value())
  156. return Error::from_code(ErrorCode::InvalidArgument, DeprecatedString::formatted("Unable to merge capability {}", name));
  157. // e. Set a property on result with name name and value value.
  158. result.set(name, value);
  159. return {};
  160. }));
  161. // 5. Return result.
  162. return result;
  163. }
  164. static bool matches_browser_version(StringView requested_version, StringView required_version)
  165. {
  166. // FIXME: Handle relative (>, >=, <. <=) comparisons. For now, require an exact match.
  167. return requested_version == required_version;
  168. }
  169. static bool matches_platform_name(StringView requested_platform_name, StringView required_platform_name)
  170. {
  171. if (requested_platform_name == required_platform_name)
  172. return true;
  173. // 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:
  174. // "linux" Any server or desktop system based upon the Linux kernel.
  175. // "mac" Any version of Apple’s macOS.
  176. // "windows" Any version of Microsoft Windows, including desktop and mobile versions.
  177. // This list is not exhaustive.
  178. // NOTE: Of the synonyms listed in the spec, the only one that differs for us is macOS.
  179. // Further, we are allowed to handle synonyms for SerenityOS.
  180. if (requested_platform_name == "mac"sv && required_platform_name == "macos"sv)
  181. return true;
  182. if (requested_platform_name == "serenity"sv && required_platform_name == "serenityos"sv)
  183. return true;
  184. return false;
  185. }
  186. // https://w3c.github.io/webdriver/#dfn-matching-capabilities
  187. static JsonValue match_capabilities(JsonObject const& capabilities)
  188. {
  189. static auto browser_name = StringView { BROWSER_NAME, strlen(BROWSER_NAME) }.to_lowercase_string();
  190. static auto platform_name = StringView { OS_STRING, strlen(OS_STRING) }.to_lowercase_string();
  191. // 1. Let matched capabilities be a JSON Object with the following entries:
  192. JsonObject matched_capabilities;
  193. // "browserName"
  194. // ASCII Lowercase name of the user agent as a string.
  195. matched_capabilities.set("browserName"sv, browser_name);
  196. // "browserVersion"
  197. // The user agent version, as a string.
  198. matched_capabilities.set("browserVersion"sv, BROWSER_VERSION);
  199. // "platformName"
  200. // ASCII Lowercase name of the current platform as a string.
  201. matched_capabilities.set("platformName"sv, platform_name);
  202. // "acceptInsecureCerts"
  203. // Boolean initially set to false, indicating the session will not implicitly trust untrusted or self-signed TLS certificates on navigation.
  204. matched_capabilities.set("acceptInsecureCerts"sv, false);
  205. // "strictFileInteractability"
  206. // Boolean initially set to false, indicating that interactability checks will be applied to <input type=file>.
  207. matched_capabilities.set("strictFileInteractability"sv, false);
  208. // "setWindowRect"
  209. // Boolean indicating whether the remote end supports all of the resizing and positioning commands.
  210. matched_capabilities.set("setWindowRect"sv, true);
  211. // 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.
  212. matched_capabilities.set("serenity:ladybird"sv, default_ladybird_options());
  213. // 3. For each name and value corresponding to capability’s own properties:
  214. auto result = capabilities.try_for_each_member([&](auto const& name, auto const& value) -> ErrorOr<void> {
  215. // a. Let match value equal value.
  216. // b. Run the substeps of the first matching name:
  217. // -> "browserName"
  218. if (name == "browserName"sv) {
  219. // If value is not a string equal to the "browserName" entry in matched capabilities, return success with data null.
  220. if (value.as_string() != matched_capabilities.get_deprecated_string(name).value())
  221. return AK::Error::from_string_view("browserName"sv);
  222. }
  223. // -> "browserVersion"
  224. else if (name == "browserVersion"sv) {
  225. // 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.
  226. // If the two values do not match, return success with data null.
  227. if (!matches_browser_version(value.as_string(), matched_capabilities.get_deprecated_string(name).value()))
  228. return AK::Error::from_string_view("browserVersion"sv);
  229. }
  230. // -> "platformName"
  231. else if (name == "platformName"sv) {
  232. // If value is not a string equal to the "platformName" entry in matched capabilities, return success with data null.
  233. if (!matches_platform_name(value.as_string(), matched_capabilities.get_deprecated_string(name).value()))
  234. return AK::Error::from_string_view("platformName"sv);
  235. }
  236. // -> "acceptInsecureCerts"
  237. else if (name == "acceptInsecureCerts"sv) {
  238. // If value is true and the endpoint node does not support insecure TLS certificates, return success with data null.
  239. if (value.as_bool())
  240. return AK::Error::from_string_view("acceptInsecureCerts"sv);
  241. }
  242. // -> "proxy"
  243. else if (name == "proxy"sv) {
  244. // 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.
  245. }
  246. // -> Otherwise
  247. else {
  248. // 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.
  249. // 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.
  250. }
  251. // c. Set a property on matched capabilities with name name and value match value.
  252. matched_capabilities.set(name, value);
  253. return {};
  254. });
  255. if (result.is_error()) {
  256. dbgln_if(WEBDRIVER_DEBUG, "Failed to match capability: {}", result.error());
  257. return JsonValue {};
  258. }
  259. // 4. Return success with data matched capabilities.
  260. return matched_capabilities;
  261. }
  262. // https://w3c.github.io/webdriver/#dfn-capabilities-processing
  263. Response process_capabilities(JsonValue const& parameters)
  264. {
  265. if (!parameters.is_object())
  266. return Error::from_code(ErrorCode::InvalidArgument, "Session parameters is not an object"sv);
  267. // 1. Let capabilities request be the result of getting the property "capabilities" from parameters.
  268. // a. If capabilities request is not a JSON Object, return error with error code invalid argument.
  269. auto maybe_capabilities_request = parameters.as_object().get_object("capabilities"sv);
  270. if (!maybe_capabilities_request.has_value())
  271. return Error::from_code(ErrorCode::InvalidArgument, "Capabilities is not an object"sv);
  272. auto const& capabilities_request = maybe_capabilities_request.value();
  273. // 2. Let required capabilities be the result of getting the property "alwaysMatch" from capabilities request.
  274. // a. If required capabilities is undefined, set the value to an empty JSON Object.
  275. JsonObject required_capabilities;
  276. if (auto capability = capabilities_request.get("alwaysMatch"sv); capability.has_value()) {
  277. // b. Let required capabilities be the result of trying to validate capabilities with argument required capabilities.
  278. required_capabilities = TRY(validate_capabilities(*capability));
  279. }
  280. // 3. Let all first match capabilities be the result of getting the property "firstMatch" from capabilities request.
  281. JsonArray all_first_match_capabilities;
  282. if (auto capabilities = capabilities_request.get("firstMatch"sv); capabilities.has_value()) {
  283. // b. If all first match capabilities is not a JSON List with one or more entries, return error with error code invalid argument.
  284. if (!capabilities->is_array() || capabilities->as_array().is_empty())
  285. return Error::from_code(ErrorCode::InvalidArgument, "Capability firstMatch must be an array with at least one entry"sv);
  286. all_first_match_capabilities = capabilities->as_array();
  287. } else {
  288. // a. If all first match capabilities is undefined, set the value to a JSON List with a single entry of an empty JSON Object.
  289. all_first_match_capabilities.must_append(JsonObject {});
  290. }
  291. // 4. Let validated first match capabilities be an empty JSON List.
  292. JsonArray validated_first_match_capabilities;
  293. validated_first_match_capabilities.ensure_capacity(all_first_match_capabilities.size());
  294. // 5. For each first match capabilities corresponding to an indexed property in all first match capabilities:
  295. TRY(all_first_match_capabilities.try_for_each([&](auto const& first_match_capabilities) -> ErrorOr<void, Error> {
  296. // a. Let validated capabilities be the result of trying to validate capabilities with argument first match capabilities.
  297. auto validated_capabilities = TRY(validate_capabilities(first_match_capabilities));
  298. // b. Append validated capabilities to validated first match capabilities.
  299. validated_first_match_capabilities.must_append(move(validated_capabilities));
  300. return {};
  301. }));
  302. // 6. Let merged capabilities be an empty List.
  303. JsonArray merged_capabilities;
  304. merged_capabilities.ensure_capacity(validated_first_match_capabilities.size());
  305. // 7. For each first match capabilities corresponding to an indexed property in validated first match capabilities:
  306. TRY(validated_first_match_capabilities.try_for_each([&](auto const& first_match_capabilities) -> ErrorOr<void, Error> {
  307. // a. Let merged be the result of trying to merge capabilities with required capabilities and first match capabilities as arguments.
  308. auto merged = TRY(merge_capabilities(required_capabilities, first_match_capabilities.as_object()));
  309. // b. Append merged to merged capabilities.
  310. merged_capabilities.must_append(move(merged));
  311. return {};
  312. }));
  313. // 8. For each capabilities corresponding to an indexed property in merged capabilities:
  314. for (auto const& capabilities : merged_capabilities.values()) {
  315. // a. Let matched capabilities be the result of trying to match capabilities with capabilities as an argument.
  316. auto matched_capabilities = match_capabilities(capabilities.as_object());
  317. // b. If matched capabilities is not null, return success with data matched capabilities.
  318. if (!matched_capabilities.is_null())
  319. return matched_capabilities;
  320. }
  321. // 9. Return success with data null.
  322. return JsonValue {};
  323. }
  324. LadybirdOptions::LadybirdOptions(JsonObject const& capabilities)
  325. {
  326. auto options = capabilities.get_object("serenity:ladybird"sv);
  327. if (!options.has_value())
  328. return;
  329. auto headless = options->get_bool("headless"sv);
  330. if (headless.has_value())
  331. this->headless = headless.value();
  332. }
  333. }