Requests.cpp 15 KB

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