Requests.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Array.h>
  7. #include <LibJS/Heap/Heap.h>
  8. #include <LibJS/Runtime/Realm.h>
  9. #include <LibWeb/Fetch/Fetching/PendingResponse.h>
  10. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  11. #include <LibWeb/URL/URL.h>
  12. namespace Web::Fetch::Infrastructure {
  13. Request::Request(JS::NonnullGCPtr<HeaderList> header_list)
  14. : m_header_list(header_list)
  15. {
  16. }
  17. void Request::visit_edges(JS::Cell::Visitor& visitor)
  18. {
  19. Base::visit_edges(visitor);
  20. visitor.visit(m_header_list);
  21. for (auto pending_response : m_pending_responses)
  22. visitor.visit(pending_response);
  23. }
  24. JS::NonnullGCPtr<Request> Request::create(JS::VM& vm)
  25. {
  26. return vm.heap().allocate_without_realm<Request>(HeaderList::create(vm));
  27. }
  28. // https://fetch.spec.whatwg.org/#concept-request-url
  29. AK::URL& Request::url()
  30. {
  31. // A request has an associated URL (a URL).
  32. // NOTE: Implementations are encouraged to make this a pointer to the first URL in request’s URL list. It is provided as a distinct field solely for the convenience of other standards hooking into Fetch.
  33. VERIFY(!m_url_list.is_empty());
  34. return m_url_list.first();
  35. }
  36. // https://fetch.spec.whatwg.org/#concept-request-url
  37. AK::URL const& Request::url() const
  38. {
  39. return const_cast<Request&>(*this).url();
  40. }
  41. // https://fetch.spec.whatwg.org/#concept-request-current-url
  42. AK::URL& Request::current_url()
  43. {
  44. // A request has an associated current URL. It is a pointer to the last URL in request’s URL list.
  45. VERIFY(!m_url_list.is_empty());
  46. return m_url_list.last();
  47. }
  48. // https://fetch.spec.whatwg.org/#concept-request-current-url
  49. AK::URL const& Request::current_url() const
  50. {
  51. return const_cast<Request&>(*this).current_url();
  52. }
  53. void Request::set_url(AK::URL url)
  54. {
  55. // Sometimes setting the URL and URL list are done as two distinct steps in the spec,
  56. // but since we know the URL is always the URL list's first item and doesn't change later
  57. // on, we can combine them.
  58. if (!m_url_list.is_empty())
  59. m_url_list.clear();
  60. m_url_list.append(move(url));
  61. }
  62. // https://fetch.spec.whatwg.org/#request-destination-script-like
  63. bool Request::destination_is_script_like() const
  64. {
  65. // A request’s destination is script-like if it is "audioworklet", "paintworklet", "script", "serviceworker", "sharedworker", or "worker".
  66. static constexpr Array script_like_destinations = {
  67. Destination::AudioWorklet,
  68. Destination::PaintWorklet,
  69. Destination::Script,
  70. Destination::ServiceWorker,
  71. Destination::SharedWorker,
  72. Destination::Worker,
  73. };
  74. return any_of(script_like_destinations, [this](auto destination) {
  75. return m_destination == destination;
  76. });
  77. }
  78. // https://fetch.spec.whatwg.org/#subresource-request
  79. bool Request::is_subresource_request() const
  80. {
  81. // A subresource request is a request whose destination is "audio", "audioworklet", "font", "image", "manifest", "paintworklet", "script", "style", "track", "video", "xslt", or the empty string.
  82. static constexpr Array subresource_request_destinations = {
  83. Destination::Audio,
  84. Destination::AudioWorklet,
  85. Destination::Font,
  86. Destination::Image,
  87. Destination::Manifest,
  88. Destination::PaintWorklet,
  89. Destination::Script,
  90. Destination::Style,
  91. Destination::Track,
  92. Destination::Video,
  93. Destination::XSLT,
  94. };
  95. return any_of(subresource_request_destinations, [this](auto destination) {
  96. return m_destination == destination;
  97. }) || !m_destination.has_value();
  98. }
  99. // https://fetch.spec.whatwg.org/#non-subresource-request
  100. bool Request::is_non_subresource_request() const
  101. {
  102. // A non-subresource request is a request whose destination is "document", "embed", "frame", "iframe", "object", "report", "serviceworker", "sharedworker", or "worker".
  103. static constexpr Array non_subresource_request_destinations = {
  104. Destination::Document,
  105. Destination::Embed,
  106. Destination::Frame,
  107. Destination::IFrame,
  108. Destination::Object,
  109. Destination::Report,
  110. Destination::ServiceWorker,
  111. Destination::SharedWorker,
  112. Destination::Worker,
  113. };
  114. return any_of(non_subresource_request_destinations, [this](auto destination) {
  115. return m_destination == destination;
  116. });
  117. }
  118. // https://fetch.spec.whatwg.org/#navigation-request
  119. bool Request::is_navigation_request() const
  120. {
  121. // A navigation request is a request whose destination is "document", "embed", "frame", "iframe", or "object".
  122. static constexpr Array navigation_request_destinations = {
  123. Destination::Document,
  124. Destination::Embed,
  125. Destination::Frame,
  126. Destination::IFrame,
  127. Destination::Object,
  128. };
  129. return any_of(navigation_request_destinations, [this](auto destination) {
  130. return m_destination == destination;
  131. });
  132. }
  133. // https://fetch.spec.whatwg.org/#concept-request-tainted-origin
  134. bool Request::has_redirect_tainted_origin() const
  135. {
  136. // A request request has a redirect-tainted origin if these steps return true:
  137. // 1. Let lastURL be null.
  138. Optional<AK::URL const&> last_url;
  139. // 2. For each url of request’s URL list:
  140. for (auto const& url : m_url_list) {
  141. // 1. If lastURL is null, then set lastURL to url and continue.
  142. if (!last_url.has_value()) {
  143. last_url = url;
  144. continue;
  145. }
  146. // 2. If url’s origin is not same origin with lastURL’s origin and request’s origin is not same origin with lastURL’s origin, then return true.
  147. auto const* request_origin = m_origin.get_pointer<HTML::Origin>();
  148. if (!URL::url_origin(url).is_same_origin(URL::url_origin(*last_url))
  149. && (request_origin == nullptr || !request_origin->is_same_origin(URL::url_origin(*last_url)))) {
  150. return true;
  151. }
  152. // 3. Set lastURL to url.
  153. last_url = url;
  154. }
  155. // 3. Return false.
  156. return false;
  157. }
  158. // https://fetch.spec.whatwg.org/#serializing-a-request-origin
  159. ErrorOr<String> Request::serialize_origin() const
  160. {
  161. // 1. If request has a redirect-tainted origin, then return "null".
  162. if (has_redirect_tainted_origin())
  163. return "null"_string;
  164. // 2. Return request’s origin, serialized.
  165. return String::from_deprecated_string(m_origin.get<HTML::Origin>().serialize());
  166. }
  167. // https://fetch.spec.whatwg.org/#byte-serializing-a-request-origin
  168. ErrorOr<ByteBuffer> Request::byte_serialize_origin() const
  169. {
  170. // Byte-serializing a request origin, given a request request, is to return the result of serializing a request origin with request, isomorphic encoded.
  171. return ByteBuffer::copy(TRY(serialize_origin()).bytes());
  172. }
  173. // https://fetch.spec.whatwg.org/#concept-request-clone
  174. WebIDL::ExceptionOr<JS::NonnullGCPtr<Request>> Request::clone(JS::Realm& realm) const
  175. {
  176. // To clone a request request, run these steps:
  177. auto& vm = realm.vm();
  178. // 1. Let newRequest be a copy of request, except for its body.
  179. auto new_request = Infrastructure::Request::create(vm);
  180. new_request->set_method(m_method);
  181. new_request->set_local_urls_only(m_local_urls_only);
  182. for (auto const& header : *m_header_list)
  183. MUST(new_request->header_list()->append(header));
  184. new_request->set_unsafe_request(m_unsafe_request);
  185. new_request->set_client(m_client);
  186. new_request->set_reserved_client(m_reserved_client);
  187. new_request->set_replaces_client_id(m_replaces_client_id);
  188. new_request->set_window(m_window);
  189. new_request->set_keepalive(m_keepalive);
  190. new_request->set_initiator_type(m_initiator_type);
  191. new_request->set_service_workers_mode(m_service_workers_mode);
  192. new_request->set_initiator(m_initiator);
  193. new_request->set_destination(m_destination);
  194. new_request->set_priority(m_priority);
  195. new_request->set_origin(m_origin);
  196. new_request->set_policy_container(m_policy_container);
  197. new_request->set_referrer(m_referrer);
  198. new_request->set_referrer_policy(m_referrer_policy);
  199. new_request->set_mode(m_mode);
  200. new_request->set_use_cors_preflight(m_use_cors_preflight);
  201. new_request->set_credentials_mode(m_credentials_mode);
  202. new_request->set_use_url_credentials(m_use_url_credentials);
  203. new_request->set_cache_mode(m_cache_mode);
  204. new_request->set_redirect_mode(m_redirect_mode);
  205. new_request->set_integrity_metadata(m_integrity_metadata);
  206. new_request->set_cryptographic_nonce_metadata(m_cryptographic_nonce_metadata);
  207. new_request->set_parser_metadata(m_parser_metadata);
  208. new_request->set_reload_navigation(m_reload_navigation);
  209. new_request->set_history_navigation(m_history_navigation);
  210. new_request->set_user_activation(m_user_activation);
  211. new_request->set_render_blocking(m_render_blocking);
  212. new_request->set_url_list(m_url_list);
  213. new_request->set_redirect_count(m_redirect_count);
  214. new_request->set_response_tainting(m_response_tainting);
  215. new_request->set_prevent_no_cache_cache_control_header_modification(m_prevent_no_cache_cache_control_header_modification);
  216. new_request->set_done(m_done);
  217. new_request->set_timing_allow_failed(m_timing_allow_failed);
  218. // 2. If request’s body is non-null, set newRequest’s body to the result of cloning request’s body.
  219. if (auto const* body = m_body.get_pointer<Body>())
  220. new_request->set_body(TRY(body->clone(realm)));
  221. // 3. Return newRequest.
  222. return new_request;
  223. }
  224. // https://fetch.spec.whatwg.org/#concept-request-add-range-header
  225. ErrorOr<void> Request::add_range_header(u64 first, Optional<u64> const& last)
  226. {
  227. // To add a range header to a request request, with an integer first, and an optional integer last, run these steps:
  228. // 1. Assert: last is not given, or first is less than or equal to last.
  229. VERIFY(!last.has_value() || first <= last.value());
  230. // 2. Let rangeValue be `bytes=`.
  231. auto range_value = MUST(ByteBuffer::copy("bytes"sv.bytes()));
  232. // 3. Serialize and isomorphic encode first, and append the result to rangeValue.
  233. TRY(range_value.try_append(TRY(String::number(first)).bytes()));
  234. // 4. Append 0x2D (-) to rangeValue.
  235. TRY(range_value.try_append('-'));
  236. // 5. If last is given, then serialize and isomorphic encode it, and append the result to rangeValue.
  237. if (last.has_value())
  238. TRY(range_value.try_append(TRY(String::number(*last)).bytes()));
  239. // 6. Append (`Range`, rangeValue) to request’s header list.
  240. auto header = Header {
  241. .name = MUST(ByteBuffer::copy("Range"sv.bytes())),
  242. .value = move(range_value),
  243. };
  244. TRY(m_header_list->append(move(header)));
  245. return {};
  246. }
  247. // https://fetch.spec.whatwg.org/#append-a-request-origin-header
  248. ErrorOr<void> Request::add_origin_header()
  249. {
  250. // 1. Let serializedOrigin be the result of byte-serializing a request origin with request.
  251. auto serialized_origin = TRY(byte_serialize_origin());
  252. // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list.
  253. if (m_response_tainting == ResponseTainting::CORS || m_mode == Mode::WebSocket) {
  254. auto header = Header {
  255. .name = MUST(ByteBuffer::copy("Origin"sv.bytes())),
  256. .value = move(serialized_origin),
  257. };
  258. TRY(m_header_list->append(move(header)));
  259. }
  260. // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
  261. else if (!StringView { m_method }.is_one_of("GET"sv, "HEAD"sv)) {
  262. // 1. If request’s mode is not "cors", then switch on request’s referrer policy:
  263. if (m_mode != Mode::CORS && m_referrer_policy.has_value()) {
  264. switch (*m_referrer_policy) {
  265. // -> "no-referrer"
  266. case ReferrerPolicy::ReferrerPolicy::NoReferrer:
  267. // Set serializedOrigin to `null`.
  268. serialized_origin = MUST(ByteBuffer::copy("null"sv.bytes()));
  269. break;
  270. // -> "no-referrer-when-downgrade"
  271. // -> "strict-origin"
  272. // -> "strict-origin-when-cross-origin"
  273. case ReferrerPolicy::ReferrerPolicy::NoReferrerWhenDowngrade:
  274. case ReferrerPolicy::ReferrerPolicy::StrictOrigin:
  275. case ReferrerPolicy::ReferrerPolicy::StrictOriginWhenCrossOrigin:
  276. // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is
  277. // not "https", then set serializedOrigin to `null`.
  278. if (m_origin.has<HTML::Origin>() && m_origin.get<HTML::Origin>().scheme() == "https"sv && current_url().scheme() != "https"sv)
  279. serialized_origin = MUST(ByteBuffer::copy("null"sv.bytes()));
  280. break;
  281. // -> "same-origin"
  282. case ReferrerPolicy::ReferrerPolicy::SameOrigin:
  283. // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin
  284. // to `null`.
  285. if (m_origin.has<HTML::Origin>() && !m_origin.get<HTML::Origin>().is_same_origin(URL::url_origin(current_url())))
  286. serialized_origin = MUST(ByteBuffer::copy("null"sv.bytes()));
  287. break;
  288. // -> Otherwise
  289. default:
  290. // Do nothing.
  291. break;
  292. }
  293. }
  294. // 2. Append (`Origin`, serializedOrigin) to request’s header list.
  295. auto header = Header {
  296. .name = MUST(ByteBuffer::copy("Origin"sv.bytes())),
  297. .value = move(serialized_origin),
  298. };
  299. TRY(m_header_list->append(move(header)));
  300. }
  301. return {};
  302. }
  303. // https://fetch.spec.whatwg.org/#cross-origin-embedder-policy-allows-credentials
  304. bool Request::cross_origin_embedder_policy_allows_credentials() const
  305. {
  306. // 1. If request’s mode is not "no-cors", then return true.
  307. if (m_mode != Mode::NoCORS)
  308. return true;
  309. // 2. If request’s client is null, then return true.
  310. if (m_client == nullptr)
  311. return true;
  312. // FIXME: 3. If request’s client’s policy container’s embedder policy’s value is not "credentialless", then return true.
  313. // 4. If request’s origin is same origin with request’s current URL’s origin and request does not have a redirect-tainted origin, then return true.
  314. // FIXME: Actually use the given origins once we have https://url.spec.whatwg.org/#concept-url-origin.
  315. if (HTML::Origin().is_same_origin(HTML::Origin()) && !has_redirect_tainted_origin())
  316. return true;
  317. // 5. Return false.
  318. return false;
  319. }
  320. }