Requests.cpp 15 KB

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