Fetching.cpp 122 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  4. * Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
  5. * Copyright (c) 2024, Jamie Mansfield <jmansfield@cadixdev.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/Base64.h>
  10. #include <AK/Debug.h>
  11. #include <AK/ScopeGuard.h>
  12. #include <LibJS/Runtime/Completion.h>
  13. #include <LibWeb/Bindings/MainThreadVM.h>
  14. #include <LibWeb/Cookie/Cookie.h>
  15. #include <LibWeb/DOM/Document.h>
  16. #include <LibWeb/DOMURL/DOMURL.h>
  17. #include <LibWeb/Fetch/BodyInit.h>
  18. #include <LibWeb/Fetch/Fetching/Checks.h>
  19. #include <LibWeb/Fetch/Fetching/Fetching.h>
  20. #include <LibWeb/Fetch/Fetching/PendingResponse.h>
  21. #include <LibWeb/Fetch/Fetching/RefCountedFlag.h>
  22. #include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
  23. #include <LibWeb/Fetch/Infrastructure/FetchController.h>
  24. #include <LibWeb/Fetch/Infrastructure/FetchParams.h>
  25. #include <LibWeb/Fetch/Infrastructure/FetchTimingInfo.h>
  26. #include <LibWeb/Fetch/Infrastructure/HTTP/Methods.h>
  27. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  28. #include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
  29. #include <LibWeb/Fetch/Infrastructure/HTTP/Statuses.h>
  30. #include <LibWeb/Fetch/Infrastructure/MimeTypeBlocking.h>
  31. #include <LibWeb/Fetch/Infrastructure/NoSniffBlocking.h>
  32. #include <LibWeb/Fetch/Infrastructure/PortBlocking.h>
  33. #include <LibWeb/Fetch/Infrastructure/Task.h>
  34. #include <LibWeb/Fetch/Infrastructure/URL.h>
  35. #include <LibWeb/FileAPI/Blob.h>
  36. #include <LibWeb/FileAPI/BlobURLStore.h>
  37. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  38. #include <LibWeb/HTML/Scripting/Environments.h>
  39. #include <LibWeb/HTML/Window.h>
  40. #include <LibWeb/HTML/WorkerGlobalScope.h>
  41. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  42. #include <LibWeb/Loader/LoadRequest.h>
  43. #include <LibWeb/Loader/ResourceLoader.h>
  44. #include <LibWeb/Platform/EventLoopPlugin.h>
  45. #include <LibWeb/ReferrerPolicy/AbstractOperations.h>
  46. #include <LibWeb/SRI/SRI.h>
  47. #include <LibWeb/SecureContexts/AbstractOperations.h>
  48. #include <LibWeb/WebIDL/DOMException.h>
  49. namespace Web::Fetch::Fetching {
  50. #define TRY_OR_IGNORE(expression) \
  51. ({ \
  52. auto&& _temporary_result = (expression); \
  53. if (_temporary_result.is_error()) \
  54. return; \
  55. static_assert(!::AK::Detail::IsLvalueReference<decltype(_temporary_result.release_value())>, \
  56. "Do not return a reference from a fallible expression"); \
  57. _temporary_result.release_value(); \
  58. })
  59. // https://fetch.spec.whatwg.org/#concept-fetch
  60. WebIDL::ExceptionOr<JS::NonnullGCPtr<Infrastructure::FetchController>> fetch(JS::Realm& realm, Infrastructure::Request& request, Infrastructure::FetchAlgorithms const& algorithms, UseParallelQueue use_parallel_queue)
  61. {
  62. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'fetch' with: request @ {}", &request);
  63. auto& vm = realm.vm();
  64. // 1. Assert: request’s mode is "navigate" or processEarlyHintsResponse is null.
  65. VERIFY(request.mode() == Infrastructure::Request::Mode::Navigate || !algorithms.process_early_hints_response());
  66. // 2. Let taskDestination be null.
  67. JS::GCPtr<JS::Object> task_destination;
  68. // 3. Let crossOriginIsolatedCapability be false.
  69. auto cross_origin_isolated_capability = HTML::CanUseCrossOriginIsolatedAPIs::No;
  70. // 4. If request’s client is non-null, then:
  71. if (request.client() != nullptr) {
  72. // 1. Set taskDestination to request’s client’s global object.
  73. task_destination = request.client()->global_object();
  74. // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin isolated capability.
  75. cross_origin_isolated_capability = request.client()->cross_origin_isolated_capability();
  76. }
  77. // FIXME: 5. If useParallelQueue is true, then set taskDestination to the result of starting a new parallel queue.
  78. (void)use_parallel_queue;
  79. (void)task_destination;
  80. // 6. Let timingInfo be a new fetch timing info whose start time and post-redirect start time are the coarsened
  81. // shared current time given crossOriginIsolatedCapability, and render-blocking is set to request’s
  82. // render-blocking.
  83. auto timing_info = Infrastructure::FetchTimingInfo::create(vm);
  84. auto now = HighResolutionTime::coarsened_shared_current_time(cross_origin_isolated_capability == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  85. timing_info->set_start_time(now);
  86. timing_info->set_post_redirect_start_time(now);
  87. timing_info->set_render_blocking(request.render_blocking());
  88. // 7. Let fetchParams be a new fetch params whose request is request, timing info is timingInfo, process request
  89. // body chunk length is processRequestBodyChunkLength, process request end-of-body is processRequestEndOfBody,
  90. // process early hints response is processEarlyHintsResponse, process response is processResponse, process
  91. // response consume body is processResponseConsumeBody, process response end-of-body is processResponseEndOfBody,
  92. // task destination is taskDestination, and cross-origin isolated capability is crossOriginIsolatedCapability.
  93. auto fetch_params = Infrastructure::FetchParams::create(vm, request, timing_info);
  94. fetch_params->set_algorithms(algorithms);
  95. if (task_destination)
  96. fetch_params->set_task_destination({ *task_destination });
  97. fetch_params->set_cross_origin_isolated_capability(cross_origin_isolated_capability);
  98. // 8. If request’s body is a byte sequence, then set request’s body to request’s body as a body.
  99. if (auto const* buffer = request.body().get_pointer<ByteBuffer>())
  100. request.set_body(TRY(Infrastructure::byte_sequence_as_body(realm, buffer->bytes())));
  101. // 9. If request’s window is "client", then set request’s window to request’s client, if request’s client’s global
  102. // object is a Window object; otherwise "no-window".
  103. auto const* window = request.window().get_pointer<Infrastructure::Request::Window>();
  104. if (window && *window == Infrastructure::Request::Window::Client) {
  105. if (is<HTML::Window>(request.client()->global_object())) {
  106. request.set_window(request.client());
  107. } else {
  108. request.set_window(Infrastructure::Request::Window::NoWindow);
  109. }
  110. }
  111. // 10. If request’s origin is "client", then set request’s origin to request’s client’s origin.
  112. auto const* origin = request.origin().get_pointer<Infrastructure::Request::Origin>();
  113. if (origin && *origin == Infrastructure::Request::Origin::Client)
  114. request.set_origin(request.client()->origin());
  115. // 12. If request’s policy container is "client", then:
  116. auto const* policy_container = request.policy_container().get_pointer<Infrastructure::Request::PolicyContainer>();
  117. if (policy_container) {
  118. VERIFY(*policy_container == Infrastructure::Request::PolicyContainer::Client);
  119. // 1. If request’s client is non-null, then set request’s policy container to a clone of request’s client’s
  120. // policy container.
  121. if (request.client() != nullptr)
  122. request.set_policy_container(request.client()->policy_container());
  123. // 2. Otherwise, set request’s policy container to a new policy container.
  124. else
  125. request.set_policy_container(HTML::PolicyContainer {});
  126. }
  127. // 13. If request’s header list does not contain `Accept`, then:
  128. if (!request.header_list()->contains("Accept"sv.bytes())) {
  129. // 1. Let value be `*/*`.
  130. auto value = "*/*"sv;
  131. // 2. A user agent should set value to the first matching statement, if any, switching on request’s
  132. // destination:
  133. if (request.destination().has_value()) {
  134. switch (*request.destination()) {
  135. // -> "document"
  136. // -> "frame"
  137. // -> "iframe"
  138. case Infrastructure::Request::Destination::Document:
  139. case Infrastructure::Request::Destination::Frame:
  140. case Infrastructure::Request::Destination::IFrame:
  141. // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
  142. value = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"sv;
  143. break;
  144. // -> "image"
  145. case Infrastructure::Request::Destination::Image:
  146. // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
  147. value = "image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5"sv;
  148. break;
  149. // -> "style"
  150. case Infrastructure::Request::Destination::Style:
  151. // `text/css,*/*;q=0.1`
  152. value = "text/css,*/*;q=0.1"sv;
  153. break;
  154. default:
  155. break;
  156. }
  157. }
  158. // 3. Append (`Accept`, value) to request’s header list.
  159. auto header = Infrastructure::Header::from_string_pair("Accept"sv, value.bytes());
  160. request.header_list()->append(move(header));
  161. }
  162. // 14. If request’s header list does not contain `Accept-Language`, then user agents should append
  163. // (`Accept-Language, an appropriate header value) to request’s header list.
  164. if (!request.header_list()->contains("Accept-Language"sv.bytes())) {
  165. auto header = Infrastructure::Header::from_string_pair("Accept-Language"sv, "*"sv);
  166. request.header_list()->append(move(header));
  167. }
  168. // 15. If request’s priority is null, then use request’s initiator, destination, and render-blocking appropriately
  169. // in setting request’s priority to a user-agent-defined object.
  170. // NOTE: The user-agent-defined object could encompass stream weight and dependency for HTTP/2, and equivalent
  171. // information used to prioritize dispatch and processing of HTTP/1 fetches.
  172. // 16. If request is a subresource request, then:
  173. if (request.is_subresource_request()) {
  174. // FIXME: 1. Let record be a new fetch record whose request is request and controller is fetchParams’s controller.
  175. // FIXME: 2. Append record to request’s client’s fetch group list of fetch records.
  176. }
  177. // 17. Run main fetch given fetchParams.
  178. (void)TRY(main_fetch(realm, fetch_params));
  179. // 18. Return fetchParams’s controller.
  180. return fetch_params->controller();
  181. }
  182. // https://fetch.spec.whatwg.org/#concept-main-fetch
  183. WebIDL::ExceptionOr<JS::GCPtr<PendingResponse>> main_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Recursive recursive)
  184. {
  185. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' with: fetch_params @ {}", &fetch_params);
  186. auto& vm = realm.vm();
  187. // 1. Let request be fetchParams’s request.
  188. auto request = fetch_params.request();
  189. // 2. Let response be null.
  190. JS::GCPtr<Infrastructure::Response> response;
  191. // 3. If request’s local-URLs-only flag is set and request’s current URL is not local, then set response to a
  192. // network error.
  193. if (request->local_urls_only() && !Infrastructure::is_local_url(request->current_url()))
  194. response = Infrastructure::Response::network_error(vm, "Request with 'local-URLs-only' flag must have a local URL"sv);
  195. // FIXME: 4. Run report Content Security Policy violations for request.
  196. // FIXME: 5. Upgrade request to a potentially trustworthy URL, if appropriate.
  197. // FIXME: 6. Upgrade a mixed content request to a potentially trustworthy URL, if appropriate.
  198. // 7. If should request be blocked due to a bad port, should fetching request be blocked as mixed content, or
  199. // should request be blocked by Content Security Policy returns blocked, then set response to a network error.
  200. if (Infrastructure::block_bad_port(request) == Infrastructure::RequestOrResponseBlocking::Blocked
  201. || false // FIXME: "should fetching request be blocked as mixed content"
  202. || false // FIXME: "should request be blocked by Content Security Policy returns blocked"
  203. ) {
  204. response = Infrastructure::Response::network_error(vm, "Request was blocked"sv);
  205. }
  206. // 8. If request’s referrer policy is the empty string, then set request’s referrer policy to request’s policy
  207. // container’s referrer policy.
  208. if (request->referrer_policy() == ReferrerPolicy::ReferrerPolicy::EmptyString) {
  209. VERIFY(request->policy_container().has<HTML::PolicyContainer>());
  210. request->set_referrer_policy(request->policy_container().get<HTML::PolicyContainer>().referrer_policy);
  211. }
  212. // 9. If request’s referrer is not "no-referrer", then set request’s referrer to the result of invoking determine
  213. // request’s referrer.
  214. // NOTE: As stated in Referrer Policy, user agents can provide the end user with options to override request’s
  215. // referrer to "no-referrer" or have it expose less sensitive information.
  216. auto const* referrer = request->referrer().get_pointer<Infrastructure::Request::Referrer>();
  217. if (!referrer || *referrer != Infrastructure::Request::Referrer::NoReferrer) {
  218. auto determined_referrer = ReferrerPolicy::determine_requests_referrer(request);
  219. if (determined_referrer.has_value())
  220. request->set_referrer(*determined_referrer);
  221. else
  222. request->set_referrer(Infrastructure::Request::Referrer::NoReferrer);
  223. }
  224. // 10. Set request’s current URL’s scheme to "https" if all of the following conditions are true:
  225. if (
  226. // - request’s current URL’s scheme is "http"
  227. request->current_url().scheme() == "http"sv
  228. // - request’s current URL’s host is a domain
  229. && DOMURL::host_is_domain(request->current_url().host())
  230. // FIXME: - Matching request’s current URL’s host per Known HSTS Host Domain Name Matching results in either a
  231. // superdomain match with an asserted includeSubDomains directive or a congruent match (with or without an
  232. // asserted includeSubDomains directive) [HSTS]; or DNS resolution for the request finds a matching HTTPS RR
  233. // per section 9.5 of [SVCB].
  234. && false
  235. ) {
  236. request->current_url().set_scheme("https"_string);
  237. }
  238. JS::SafeFunction<WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>>()> get_response = [&realm, &vm, &fetch_params, request]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> {
  239. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' get_response() function");
  240. // -> fetchParams’s preloaded response candidate is not null
  241. if (!fetch_params.preloaded_response_candidate().has<Empty>()) {
  242. // 1. Wait until fetchParams’s preloaded response candidate is not "pending".
  243. HTML::main_thread_event_loop().spin_until([&] {
  244. return !fetch_params.preloaded_response_candidate().has<Infrastructure::FetchParams::PreloadedResponseCandidatePendingTag>();
  245. });
  246. // 2. Assert: fetchParams’s preloaded response candidate is a response.
  247. VERIFY(fetch_params.preloaded_response_candidate().has<JS::NonnullGCPtr<Infrastructure::Response>>());
  248. // 3. Return fetchParams’s preloaded response candidate.
  249. return PendingResponse::create(vm, request, fetch_params.preloaded_response_candidate().get<JS::NonnullGCPtr<Infrastructure::Response>>());
  250. }
  251. // -> request’s current URL’s origin is same origin with request’s origin, and request’s response tainting
  252. // is "basic"
  253. // -> request’s current URL’s scheme is "data"
  254. // -> request’s mode is "navigate" or "websocket"
  255. else if (
  256. (request->origin().has<HTML::Origin>() && DOMURL::url_origin(request->current_url()).is_same_origin(request->origin().get<HTML::Origin>()) && request->response_tainting() == Infrastructure::Request::ResponseTainting::Basic)
  257. || request->current_url().scheme() == "data"sv
  258. || (request->mode() == Infrastructure::Request::Mode::Navigate || request->mode() == Infrastructure::Request::Mode::WebSocket)) {
  259. // 1. Set request’s response tainting to "basic".
  260. request->set_response_tainting(Infrastructure::Request::ResponseTainting::Basic);
  261. // 2. Return the result of running scheme fetch given fetchParams.
  262. return scheme_fetch(realm, fetch_params);
  263. // NOTE: HTML assigns any documents and workers created from URLs whose scheme is "data" a unique
  264. // opaque origin. Service workers can only be created from URLs whose scheme is an HTTP(S) scheme.
  265. }
  266. // -> request’s mode is "same-origin"
  267. else if (request->mode() == Infrastructure::Request::Mode::SameOrigin) {
  268. // Return a network error.
  269. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'same-origin' mode must have same URL and request origin"sv));
  270. }
  271. // -> request’s mode is "no-cors"
  272. else if (request->mode() == Infrastructure::Request::Mode::NoCORS) {
  273. // 1. If request’s redirect mode is not "follow", then return a network error.
  274. if (request->redirect_mode() != Infrastructure::Request::RedirectMode::Follow)
  275. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'no-cors' mode must have redirect mode set to 'follow'"sv));
  276. // 2. Set request’s response tainting to "opaque".
  277. request->set_response_tainting(Infrastructure::Request::ResponseTainting::Opaque);
  278. // 3. Return the result of running scheme fetch given fetchParams.
  279. return scheme_fetch(realm, fetch_params);
  280. }
  281. // -> request’s current URL’s scheme is not an HTTP(S) scheme
  282. else if (!Infrastructure::is_http_or_https_scheme(request->current_url().scheme())) {
  283. // NOTE: At this point all other request modes have been handled. Ensure we're not lying in the error message :^)
  284. VERIFY(request->mode() == Infrastructure::Request::Mode::CORS);
  285. // Return a network error.
  286. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'cors' mode must have URL with HTTP or HTTPS scheme"sv));
  287. }
  288. // -> request’s use-CORS-preflight flag is set
  289. // -> request’s unsafe-request flag is set and either request’s method is not a CORS-safelisted method or
  290. // CORS-unsafe request-header names with request’s header list is not empty
  291. else if (
  292. request->use_cors_preflight()
  293. || (request->unsafe_request()
  294. && (!Infrastructure::is_cors_safelisted_method(request->method())
  295. || !Infrastructure::get_cors_unsafe_header_names(request->header_list()).is_empty()))) {
  296. // 1. Set request’s response tainting to "cors".
  297. request->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
  298. auto returned_pending_response = PendingResponse::create(vm, request);
  299. // 2. Let corsWithPreflightResponse be the result of running HTTP fetch given fetchParams and true.
  300. auto cors_with_preflight_response = TRY(http_fetch(realm, fetch_params, MakeCORSPreflight::Yes));
  301. cors_with_preflight_response->when_loaded([returned_pending_response](JS::NonnullGCPtr<Infrastructure::Response> cors_with_preflight_response) {
  302. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' cors_with_preflight_response load callback");
  303. // 3. If corsWithPreflightResponse is a network error, then clear cache entries using request.
  304. if (cors_with_preflight_response->is_network_error()) {
  305. // FIXME: Clear cache entries
  306. }
  307. // 4. Return corsWithPreflightResponse.
  308. returned_pending_response->resolve(cors_with_preflight_response);
  309. });
  310. return returned_pending_response;
  311. }
  312. // -> Otherwise
  313. else {
  314. // 1. Set request’s response tainting to "cors".
  315. request->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
  316. // 2. Return the result of running HTTP fetch given fetchParams.
  317. return http_fetch(realm, fetch_params);
  318. }
  319. };
  320. if (recursive == Recursive::Yes) {
  321. // 12. If response is null, then set response to the result of running the steps corresponding to the first
  322. // matching statement:
  323. auto pending_response = !response
  324. ? TRY(get_response())
  325. : PendingResponse::create(vm, request, *response);
  326. // 13. If recursive is true, then return response.
  327. return pending_response;
  328. }
  329. // 11. If recursive is false, then run the remaining steps in parallel.
  330. Platform::EventLoopPlugin::the().deferred_invoke([&realm, &vm, &fetch_params, request, response, get_response = move(get_response)] {
  331. // 12. If response is null, then set response to the result of running the steps corresponding to the first
  332. // matching statement:
  333. auto pending_response = PendingResponse::create(vm, request, Infrastructure::Response::create(vm));
  334. if (!response) {
  335. auto pending_response_or_error = get_response();
  336. if (pending_response_or_error.is_error())
  337. return;
  338. pending_response = pending_response_or_error.release_value();
  339. }
  340. pending_response->when_loaded([&realm, &vm, &fetch_params, request, response, response_was_null = !response](JS::NonnullGCPtr<Infrastructure::Response> resolved_response) mutable {
  341. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'main fetch' pending_response load callback");
  342. if (response_was_null)
  343. response = resolved_response;
  344. // 14. If response is not a network error and response is not a filtered response, then:
  345. if (!response->is_network_error() && !is<Infrastructure::FilteredResponse>(*response)) {
  346. // 1. If request’s response tainting is "cors", then:
  347. if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS) {
  348. // 1. Let headerNames be the result of extracting header list values given
  349. // `Access-Control-Expose-Headers` and response’s header list.
  350. auto header_names_or_failure = Infrastructure::extract_header_list_values("Access-Control-Expose-Headers"sv.bytes(), response->header_list());
  351. auto header_names = header_names_or_failure.has<Vector<ByteBuffer>>() ? header_names_or_failure.get<Vector<ByteBuffer>>() : Vector<ByteBuffer> {};
  352. // 2. If request’s credentials mode is not "include" and headerNames contains `*`, then set
  353. // response’s CORS-exposed header-name list to all unique header names in response’s header
  354. // list.
  355. if (request->credentials_mode() != Infrastructure::Request::CredentialsMode::Include && header_names.contains_slow("*"sv.bytes())) {
  356. auto unique_header_names = response->header_list()->unique_names();
  357. response->set_cors_exposed_header_name_list(move(unique_header_names));
  358. }
  359. // 3. Otherwise, if headerNames is not null or failure, then set response’s CORS-exposed
  360. // header-name list to headerNames.
  361. else if (!header_names.is_empty()) {
  362. response->set_cors_exposed_header_name_list(move(header_names));
  363. }
  364. }
  365. // 2. Set response to the following filtered response with response as its internal response, depending
  366. // on request’s response tainting:
  367. response = [&]() -> JS::NonnullGCPtr<Infrastructure::Response> {
  368. switch (request->response_tainting()) {
  369. // -> "basic"
  370. case Infrastructure::Request::ResponseTainting::Basic:
  371. // basic filtered response
  372. return Infrastructure::BasicFilteredResponse::create(vm, *response);
  373. // -> "cors"
  374. case Infrastructure::Request::ResponseTainting::CORS:
  375. // CORS filtered response
  376. return Infrastructure::CORSFilteredResponse::create(vm, *response);
  377. // -> "opaque"
  378. case Infrastructure::Request::ResponseTainting::Opaque:
  379. // opaque filtered response
  380. return Infrastructure::OpaqueFilteredResponse::create(vm, *response);
  381. default:
  382. VERIFY_NOT_REACHED();
  383. }
  384. }();
  385. }
  386. // 15. Let internalResponse be response, if response is a network error, and response’s internal response
  387. // otherwise.
  388. auto internal_response = response->is_network_error()
  389. ? JS::NonnullGCPtr { *response }
  390. : static_cast<Infrastructure::FilteredResponse&>(*response).internal_response();
  391. // 16. If internalResponse’s URL list is empty, then set it to a clone of request’s URL list.
  392. // NOTE: A response’s URL list can be empty (for example, when the response represents an about URL).
  393. if (internal_response->url_list().is_empty())
  394. internal_response->set_url_list(request->url_list());
  395. // 17. If request has a redirect-tainted origin, then set internalResponse’s has-cross-origin-redirects to true.
  396. if (request->has_redirect_tainted_origin())
  397. internal_response->set_has_cross_origin_redirects(true);
  398. // 18. If request’s timing allow failed flag is unset, then set internalResponse’s timing allow passed flag.
  399. if (!request->timing_allow_failed())
  400. internal_response->set_timing_allow_passed(true);
  401. // 19. If response is not a network error and any of the following returns blocked
  402. if (!response->is_network_error() && (
  403. // FIXME: - should internalResponse to request be blocked as mixed content
  404. false
  405. // FIXME: - should internalResponse to request be blocked by Content Security Policy
  406. || false
  407. // - should internalResponse to request be blocked due to its MIME type
  408. || Infrastructure::should_response_to_request_be_blocked_due_to_its_mime_type(internal_response, request) == Infrastructure::RequestOrResponseBlocking::Blocked
  409. // - should internalResponse to request be blocked due to nosniff
  410. || Infrastructure::should_response_to_request_be_blocked_due_to_nosniff(internal_response, request) == Infrastructure::RequestOrResponseBlocking::Blocked)) {
  411. // then set response and internalResponse to a network error.
  412. response = internal_response = Infrastructure::Response::network_error(vm, "Response was blocked"_string);
  413. }
  414. // 20. If response’s type is "opaque", internalResponse’s status is 206, internalResponse’s range-requested
  415. // flag is set, and request’s header list does not contain `Range`, then set response and
  416. // internalResponse to a network error.
  417. // NOTE: Traditionally, APIs accept a ranged response even if a range was not requested. This prevents a
  418. // partial response from an earlier ranged request being provided to an API that did not make a range
  419. // request.
  420. if (response->type() == Infrastructure::Response::Type::Opaque
  421. && internal_response->status() == 206
  422. && internal_response->range_requested()
  423. && !request->header_list()->contains("Range"sv.bytes())) {
  424. response = internal_response = Infrastructure::Response::network_error(vm, "Response has status 206 and 'range-requested' flag set, but request has no 'Range' header"_string);
  425. }
  426. // 21. If response is not a network error and either request’s method is `HEAD` or `CONNECT`, or
  427. // internalResponse’s status is a null body status, set internalResponse’s body to null and disregard
  428. // any enqueuing toward it (if any).
  429. // NOTE: This standardizes the error handling for servers that violate HTTP.
  430. if (!response->is_network_error() && (StringView { request->method() }.is_one_of("HEAD"sv, "CONNECT"sv) || Infrastructure::is_null_body_status(internal_response->status())))
  431. internal_response->set_body({});
  432. // 22. If request’s integrity metadata is not the empty string, then:
  433. if (!request->integrity_metadata().is_empty()) {
  434. // 1. Let processBodyError be this step: run fetch response handover given fetchParams and a network
  435. // error.
  436. auto process_body_error = JS::create_heap_function(vm.heap(), [&realm, &vm, &fetch_params](JS::GCPtr<WebIDL::DOMException>) {
  437. fetch_response_handover(realm, fetch_params, Infrastructure::Response::network_error(vm, "Response body could not be processed"sv));
  438. });
  439. // 2. If response’s body is null, then run processBodyError and abort these steps.
  440. if (!response->body()) {
  441. process_body_error->function()({});
  442. return;
  443. }
  444. // 3. Let processBody given bytes be these steps:
  445. auto process_body = JS::create_heap_function(vm.heap(), [&realm, request, response, &fetch_params, process_body_error = move(process_body_error)](ByteBuffer bytes) {
  446. // 1. If bytes do not match request’s integrity metadata, then run processBodyError and abort these steps.
  447. if (!TRY_OR_IGNORE(SRI::do_bytes_match_metadata_list(bytes, request->integrity_metadata()))) {
  448. process_body_error->function()({});
  449. return;
  450. }
  451. // 2. Set response’s body to bytes as a body.
  452. response->set_body(TRY_OR_IGNORE(Infrastructure::byte_sequence_as_body(realm, bytes)));
  453. // 3. Run fetch response handover given fetchParams and response.
  454. fetch_response_handover(realm, fetch_params, *response);
  455. });
  456. // 4. Fully read response’s body given processBody and processBodyError.
  457. response->body()->fully_read(realm, process_body, process_body_error, fetch_params.task_destination());
  458. }
  459. // 23. Otherwise, run fetch response handover given fetchParams and response.
  460. else {
  461. fetch_response_handover(realm, fetch_params, *response);
  462. }
  463. });
  464. });
  465. return JS::GCPtr<PendingResponse> {};
  466. }
  467. // https://fetch.spec.whatwg.org/#fetch-finale
  468. void fetch_response_handover(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Infrastructure::Response& response)
  469. {
  470. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'fetch response handover' with: fetch_params @ {}, response @ {}", &fetch_params, &response);
  471. auto& vm = realm.vm();
  472. // 1. Let timingInfo be fetchParams’s timing info.
  473. auto timing_info = fetch_params.timing_info();
  474. // 2. If response is not a network error and fetchParams’s request’s client is a secure context, then set
  475. // timingInfo’s server-timing headers to the result of getting, decoding, and splitting `Server-Timing` from
  476. // response’s header list.
  477. // The user agent may decide to expose `Server-Timing` headers to non-secure contexts requests as well.
  478. auto client = fetch_params.request()->client();
  479. if (!response.is_network_error() && client != nullptr && HTML::is_secure_context(*client)) {
  480. auto server_timing_headers = response.header_list()->get_decode_and_split("Server-Timing"sv.bytes());
  481. if (server_timing_headers.has_value())
  482. timing_info->set_server_timing_headers(server_timing_headers.release_value());
  483. }
  484. // 3. Let processResponseEndOfBody be the following steps:
  485. auto process_response_end_of_body = [&vm, &response, &fetch_params, timing_info] {
  486. // 1. Let unsafeEndTime be the unsafe shared current time.
  487. auto unsafe_end_time = HighResolutionTime::unsafe_shared_current_time();
  488. // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s full timing
  489. // info to fetchParams’s timing info.
  490. if (fetch_params.request()->destination() == Infrastructure::Request::Destination::Document)
  491. fetch_params.controller()->set_full_timing_info(fetch_params.timing_info());
  492. // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:
  493. fetch_params.controller()->set_report_timing_steps([&vm, &response, &fetch_params, timing_info, unsafe_end_time](JS::Object const& global) mutable {
  494. // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return.
  495. if (!Infrastructure::is_http_or_https_scheme(fetch_params.request()->url().scheme()))
  496. return;
  497. // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global.
  498. timing_info->set_end_time(HighResolutionTime::relative_high_resolution_time(unsafe_end_time, global));
  499. // 3. Let cacheState be response’s cache state.
  500. auto cache_state = response.cache_state();
  501. // 4. Let bodyInfo be response’s body info.
  502. auto body_info = response.body_info();
  503. // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an
  504. // opaque timing info for timingInfo, set bodyInfo to a new response body info, and set cacheState to
  505. // the empty string.
  506. // NOTE: This covers the case of response being a network error.
  507. if (!response.timing_allow_passed()) {
  508. timing_info = Infrastructure::create_opaque_timing_info(vm, timing_info);
  509. body_info = Infrastructure::Response::BodyInfo {};
  510. cache_state = {};
  511. }
  512. // 6. Let responseStatus be 0 if fetchParams’s request’s mode is "navigate" and response’s has-cross-origin-redirects is true; otherwise response’s status.
  513. auto response_status = fetch_params.request()->mode() == Infrastructure::Request::Mode::Navigate && response.has_cross_origin_redirects()
  514. ? 0
  515. : response.status();
  516. // FIXME: 7. If fetchParams’s request’s initiator type is not null, then mark resource timing given timingInfo,
  517. // request’s URL, request’s initiator type, global, cacheState, bodyInfo, and responseStatus.
  518. (void)timing_info;
  519. (void)global;
  520. (void)cache_state;
  521. (void)body_info;
  522. (void)response_status;
  523. });
  524. // 4. Let processResponseEndOfBodyTask be the following steps:
  525. auto process_response_end_of_body_task = JS::create_heap_function(vm.heap(), [&fetch_params, &response] {
  526. // 1. Set fetchParams’s request’s done flag.
  527. fetch_params.request()->set_done(true);
  528. // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process response
  529. // end-of-body given response.
  530. if (fetch_params.algorithms()->process_response_end_of_body())
  531. (fetch_params.algorithms()->process_response_end_of_body())(response);
  532. // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s global
  533. // object is fetchParams’s task destination, then run fetchParams’s controller’s report timing steps
  534. // given fetchParams’s request’s client’s global object.
  535. auto client = fetch_params.request()->client();
  536. auto const* task_destination_global_object = fetch_params.task_destination().get_pointer<JS::NonnullGCPtr<JS::Object>>();
  537. if (client != nullptr && task_destination_global_object != nullptr) {
  538. if (fetch_params.request()->initiator_type().has_value() && &client->global_object() == task_destination_global_object->ptr())
  539. fetch_params.controller()->report_timing(client->global_object());
  540. }
  541. });
  542. // FIXME: Handle 'parallel queue' task destination
  543. auto task_destination = fetch_params.task_destination().get<JS::NonnullGCPtr<JS::Object>>();
  544. // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination.
  545. Infrastructure::queue_fetch_task(fetch_params.controller(), task_destination, move(process_response_end_of_body_task));
  546. };
  547. // FIXME: Handle 'parallel queue' task destination
  548. auto task_destination = fetch_params.task_destination().get<JS::NonnullGCPtr<JS::Object>>();
  549. // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s process response
  550. // given response, with fetchParams’s task destination.
  551. if (fetch_params.algorithms()->process_response()) {
  552. Infrastructure::queue_fetch_task(fetch_params.controller(), task_destination, JS::create_heap_function(vm.heap(), [&fetch_params, &response]() {
  553. fetch_params.algorithms()->process_response()(response);
  554. }));
  555. }
  556. // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response.
  557. auto internal_response = response.is_network_error() ? JS::NonnullGCPtr { response } : response.unsafe_response();
  558. // 6. If internalResponse’s body is null, then run processResponseEndOfBody.
  559. if (!internal_response->body()) {
  560. process_response_end_of_body();
  561. }
  562. // 7. Otherwise:
  563. else {
  564. // FIXME: 1. Let transformStream be a new TransformStream.
  565. // FIXME: 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.
  566. // FIXME: 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm set
  567. // to processResponseEndOfBody.
  568. // FIXME: 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.
  569. }
  570. // 8. If fetchParams’s process response consume body is non-null, then:
  571. if (fetch_params.algorithms()->process_response_consume_body()) {
  572. // 1. Let processBody given nullOrBytes be this step: run fetchParams’s process response consume body given
  573. // response and nullOrBytes.
  574. auto process_body = JS::create_heap_function(vm.heap(), [&fetch_params, &response](ByteBuffer null_or_bytes) {
  575. (fetch_params.algorithms()->process_response_consume_body())(response, null_or_bytes);
  576. });
  577. // 2. Let processBodyError be this step: run fetchParams’s process response consume body given response and
  578. // failure.
  579. auto process_body_error = JS::create_heap_function(vm.heap(), [&fetch_params, &response](JS::GCPtr<WebIDL::DOMException>) {
  580. (fetch_params.algorithms()->process_response_consume_body())(response, Infrastructure::FetchAlgorithms::ConsumeBodyFailureTag {});
  581. });
  582. // 3. If internalResponse's body is null, then queue a fetch task to run processBody given null, with
  583. // fetchParams’s task destination.
  584. if (!internal_response->body()) {
  585. Infrastructure::queue_fetch_task(fetch_params.controller(), task_destination, JS::create_heap_function(vm.heap(), [process_body = move(process_body)]() {
  586. process_body->function()({});
  587. }));
  588. }
  589. // 4. Otherwise, fully read internalResponse body given processBody, processBodyError, and fetchParams’s task
  590. // destination.
  591. else {
  592. internal_response->body()->fully_read(realm, process_body, process_body_error, fetch_params.task_destination());
  593. }
  594. }
  595. }
  596. // https://fetch.spec.whatwg.org/#concept-scheme-fetch
  597. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> scheme_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params)
  598. {
  599. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'scheme fetch' with: fetch_params @ {}", &fetch_params);
  600. auto& vm = realm.vm();
  601. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  602. if (fetch_params.is_canceled())
  603. return PendingResponse::create(vm, fetch_params.request(), Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  604. // 2. Let request be fetchParams’s request.
  605. auto request = fetch_params.request();
  606. // 3. Switch on request’s current URL’s scheme and run the associated steps:
  607. // -> "about"
  608. if (request->current_url().scheme() == "about"sv) {
  609. // If request’s current URL’s path is the string "blank", then return a new response whose status message is
  610. // `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », and body is the empty byte sequence as
  611. // a body.
  612. // NOTE: URLs such as "about:config" are handled during navigation and result in a network error in the context
  613. // of fetching.
  614. if (request->current_url().serialize_path() == "blank"sv) {
  615. auto response = Infrastructure::Response::create(vm);
  616. response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
  617. auto header = Infrastructure::Header::from_string_pair("Content-Type"sv, "text/html;charset=utf-8"sv);
  618. response->header_list()->append(move(header));
  619. response->set_body(MUST(Infrastructure::byte_sequence_as_body(realm, ""sv.bytes())));
  620. return PendingResponse::create(vm, request, response);
  621. }
  622. // FIXME: This is actually wrong, see note above.
  623. return TRY(nonstandard_resource_loader_file_or_http_network_fetch(realm, fetch_params));
  624. }
  625. // -> "blob"
  626. else if (request->current_url().scheme() == "blob"sv) {
  627. auto const& store = FileAPI::blob_url_store();
  628. // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
  629. auto blob_url_entry = store.get(TRY_OR_THROW_OOM(vm, request->current_url().to_string()));
  630. // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s object is not a Blob object,
  631. // then return a network error. [FILEAPI]
  632. if (request->method() != "GET"sv.bytes() || !blob_url_entry.has_value()) {
  633. // FIXME: Handle "blobURLEntry’s object is not a Blob object". It could be a MediaSource object, but we
  634. // have not yet implemented the Media Source Extensions spec.
  635. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has an invalid 'blob:' URL"sv));
  636. }
  637. // 3. Let blob be blobURLEntry’s object.
  638. auto const& blob = blob_url_entry->object;
  639. // 4. Let response be a new response.
  640. auto response = Infrastructure::Response::create(vm);
  641. // 5. Let fullLength be blob’s size.
  642. auto full_length = blob->size();
  643. // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded.
  644. auto serialized_full_length = TRY_OR_THROW_OOM(vm, String::number(full_length));
  645. // 7. Let type be blob’s type.
  646. auto const& type = blob->type();
  647. // 8. If request’s header list does not contain `Range`:
  648. if (!request->header_list()->contains("Range"sv.bytes())) {
  649. // 1. Let bodyWithType be the result of safely extracting blob.
  650. auto body_with_type = TRY(safely_extract_body(realm, blob));
  651. // 2. Set response’s status message to `OK`.
  652. response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
  653. // 3. Set response’s body to bodyWithType’s body.
  654. response->set_body(move(body_with_type.body));
  655. // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ».
  656. auto content_length_header = Infrastructure::Header::from_string_pair("Content-Length"sv, serialized_full_length);
  657. response->header_list()->append(move(content_length_header));
  658. auto content_type_header = Infrastructure::Header::from_string_pair("Content-Type"sv, type);
  659. response->header_list()->append(move(content_type_header));
  660. }
  661. // FIXME: 9. Otherwise:
  662. else {
  663. // 1. Set response’s range-requested flag.
  664. // 2. Let rangeHeader be the result of getting `Range` from request’s header list.
  665. // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true.
  666. // 4. If rangeValue is failure, then return a network error.
  667. // 5. Let (rangeStart, rangeEnd) be rangeValue.
  668. // 6. If rangeStart is null:
  669. // 1. Set rangeStart to fullLength − rangeEnd.
  670. // 2. Set rangeEnd to rangeStart + rangeEnd − 1.
  671. // 7. Otherwise:
  672. // 1. If rangeStart is greater than or equal to fullLength, then return a network error.
  673. // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set rangeEnd to fullLength − 1.
  674. // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart, rangeEnd + 1, and type.
  675. // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob.
  676. // 10. Set response’s body to slicedBodyWithType’s body.
  677. // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded.
  678. // 12. Let contentRange be `bytes `.
  679. // 13. Append rangeStart, serialized and isomorphic encoded, to contentRange.
  680. // 14. Append 0x2D (-) to contentRange.
  681. // 15. Append rangeEnd, serialized and isomorphic encoded to contentRange.
  682. // 16. Append 0x2F (/) to contentRange.
  683. // 17. Append serializedFullLength to contentRange.
  684. // 18. Set response’s status to 206.
  685. // 19. Set response’s status message to `Partial Content`.
  686. // 20. Set response’s header list to « (`Content-Length`, serializedSlicedLength), (`Content-Type`, type), (`Content-Range`, contentRange) ».
  687. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has a 'blob:' URL with a Content-Range header, which is currently unsupported"sv));
  688. }
  689. // 10. Return response.
  690. return PendingResponse::create(vm, request, response);
  691. }
  692. // -> "data"
  693. else if (request->current_url().scheme() == "data"sv) {
  694. // 1. Let dataURLStruct be the result of running the data: URL processor on request’s current URL.
  695. auto data_url_struct = Infrastructure::process_data_url(request->current_url());
  696. // 2. If dataURLStruct is failure, then return a network error.
  697. if (data_url_struct.is_error())
  698. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Failed to process 'data:' URL"sv));
  699. // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
  700. // FIXME: Serialize MIME type.
  701. auto const& mime_type = data_url_struct.value().mime_type;
  702. // 4. Return a new response whose status message is `OK`, header list is « (`Content-Type`, mimeType) », and
  703. // body is dataURLStruct’s body as a body.
  704. auto response = Infrastructure::Response::create(vm);
  705. response->set_status_message(MUST(ByteBuffer::copy("OK"sv.bytes())));
  706. auto header = Infrastructure::Header::from_string_pair("Content-Type"sv, mime_type);
  707. response->header_list()->append(move(header));
  708. response->set_body(TRY(Infrastructure::byte_sequence_as_body(realm, data_url_struct.value().body)));
  709. return PendingResponse::create(vm, request, response);
  710. }
  711. // -> "file"
  712. else if (request->current_url().scheme() == "file"sv) {
  713. // For now, unfortunate as it is, file: URLs are left as an exercise for the reader.
  714. // When in doubt, return a network error.
  715. return TRY(nonstandard_resource_loader_file_or_http_network_fetch(realm, fetch_params));
  716. }
  717. // -> HTTP(S) scheme
  718. else if (Infrastructure::is_http_or_https_scheme(request->current_url().scheme())) {
  719. // Return the result of running HTTP fetch given fetchParams.
  720. return http_fetch(realm, fetch_params);
  721. }
  722. // AD-HOC: "resource"
  723. else if (request->current_url().scheme() == "resource"sv) {
  724. return TRY(nonstandard_resource_loader_file_or_http_network_fetch(realm, fetch_params));
  725. }
  726. // 4. Return a network error.
  727. auto message = request->current_url().scheme() == "about"sv
  728. ? "Request has invalid 'about:' URL, only 'about:blank' can be fetched"_string
  729. : "Request URL has invalid scheme, must be one of 'about', 'blob', 'data', 'file', 'http', or 'https'"_string;
  730. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, move(message)));
  731. }
  732. // https://fetch.spec.whatwg.org/#concept-http-fetch
  733. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, MakeCORSPreflight make_cors_preflight)
  734. {
  735. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' with: fetch_params @ {}, make_cors_preflight = {}",
  736. &fetch_params, make_cors_preflight == MakeCORSPreflight::Yes ? "Yes"sv : "No"sv);
  737. auto& vm = realm.vm();
  738. // 1. Let request be fetchParams’s request.
  739. auto request = fetch_params.request();
  740. // 2. Let response be null.
  741. JS::GCPtr<Infrastructure::Response> response;
  742. // 3. Let actualResponse be null.
  743. JS::GCPtr<Infrastructure::Response> actual_response;
  744. // 4. If request’s service-workers mode is "all", then:
  745. if (request->service_workers_mode() == Infrastructure::Request::ServiceWorkersMode::All) {
  746. // 1. Let requestForServiceWorker be a clone of request.
  747. auto request_for_service_worker = request->clone(realm);
  748. // 2. If requestForServiceWorker’s body is non-null, then:
  749. if (!request_for_service_worker->body().has<Empty>()) {
  750. // FIXME: 1. Let transformStream be a new TransformStream.
  751. // FIXME: 2. Let transformAlgorithm given chunk be these steps:
  752. // FIXME: 3. Set up transformStream with transformAlgorithm set to transformAlgorithm.
  753. // FIXME: 4. Set requestForServiceWorker’s body’s stream to the result of requestForServiceWorker’s body’s stream
  754. // piped through transformStream.
  755. }
  756. // 3. Let serviceWorkerStartTime be the coarsened shared current time given fetchParams’s cross-origin isolated
  757. // capability.
  758. auto service_worker_start_time = HighResolutionTime::coarsened_shared_current_time(fetch_params.cross_origin_isolated_capability() == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  759. // FIXME: 4. Set response to the result of invoking handle fetch for requestForServiceWorker, with fetchParams’s
  760. // controller and fetchParams’s cross-origin isolated capability.
  761. // 5. If response is not null, then:
  762. if (response) {
  763. // 1. Set fetchParams’s timing info’s final service worker start time to serviceWorkerStartTime.
  764. fetch_params.timing_info()->set_final_service_worker_start_time(service_worker_start_time);
  765. // 2. If request’s body is non-null, then cancel request’s body with undefined.
  766. if (!request->body().has<Empty>()) {
  767. // FIXME: Implement cancelling streams
  768. }
  769. // 3. Set actualResponse to response, if response is not a filtered response, and to response’s internal
  770. // response otherwise.
  771. actual_response = !is<Infrastructure::FilteredResponse>(*response)
  772. ? JS::NonnullGCPtr { *response }
  773. : static_cast<Infrastructure::FilteredResponse const&>(*response).internal_response();
  774. // 4. If one of the following is true
  775. if (
  776. // - response’s type is "error"
  777. response->type() == Infrastructure::Response::Type::Error
  778. // - request’s mode is "same-origin" and response’s type is "cors"
  779. || (request->mode() == Infrastructure::Request::Mode::SameOrigin && response->type() == Infrastructure::Response::Type::CORS)
  780. // - request’s mode is not "no-cors" and response’s type is "opaque"
  781. || (request->mode() != Infrastructure::Request::Mode::NoCORS && response->type() == Infrastructure::Response::Type::Opaque)
  782. // - request’s redirect mode is not "manual" and response’s type is "opaqueredirect"
  783. || (request->redirect_mode() != Infrastructure::Request::RedirectMode::Manual && response->type() == Infrastructure::Response::Type::OpaqueRedirect)
  784. // - request’s redirect mode is not "follow" and response’s URL list has more than one item.
  785. || (request->redirect_mode() != Infrastructure::Request::RedirectMode::Follow && response->url_list().size() > 1)) {
  786. // then return a network error.
  787. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Invalid request/response state combination"sv));
  788. }
  789. }
  790. }
  791. JS::GCPtr<PendingResponse> pending_actual_response;
  792. auto returned_pending_response = PendingResponse::create(vm, request);
  793. // 5. If response is null, then:
  794. if (!response) {
  795. // 1. If makeCORSPreflight is true and one of these conditions is true:
  796. // NOTE: This step checks the CORS-preflight cache and if there is no suitable entry it performs a
  797. // CORS-preflight fetch which, if successful, populates the cache. The purpose of the CORS-preflight
  798. // fetch is to ensure the fetched resource is familiar with the CORS protocol. The cache is there to
  799. // minimize the number of CORS-preflight fetches.
  800. JS::GCPtr<PendingResponse> pending_preflight_response;
  801. if (make_cors_preflight == MakeCORSPreflight::Yes && (
  802. // - There is no method cache entry match for request’s method using request, and either request’s
  803. // method is not a CORS-safelisted method or request’s use-CORS-preflight flag is set.
  804. // FIXME: We currently have no cache, so there will always be no method cache entry.
  805. (!Infrastructure::is_cors_safelisted_method(request->method()) || request->use_cors_preflight())
  806. // - There is at least one item in the CORS-unsafe request-header names with request’s header list for
  807. // which there is no header-name cache entry match using request.
  808. // FIXME: We currently have no cache, so there will always be no header-name cache entry.
  809. || !Infrastructure::get_cors_unsafe_header_names(request->header_list()).is_empty())) {
  810. // 1. Let preflightResponse be the result of running CORS-preflight fetch given request.
  811. pending_preflight_response = TRY(cors_preflight_fetch(realm, request));
  812. // NOTE: Step 2 is performed in pending_preflight_response's load callback below.
  813. }
  814. auto fetch_main_content = [request = JS::make_handle(request), realm = JS::make_handle(realm), fetch_params = JS::make_handle(fetch_params)]() -> WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> {
  815. // 2. If request’s redirect mode is "follow", then set request’s service-workers mode to "none".
  816. // NOTE: Redirects coming from the network (as opposed to from a service worker) are not to be exposed to a
  817. // service worker.
  818. if (request->redirect_mode() == Infrastructure::Request::RedirectMode::Follow)
  819. request->set_service_workers_mode(Infrastructure::Request::ServiceWorkersMode::None);
  820. // 3. Set response and actualResponse to the result of running HTTP-network-or-cache fetch given fetchParams.
  821. return http_network_or_cache_fetch(*realm, *fetch_params);
  822. };
  823. if (pending_preflight_response) {
  824. pending_actual_response = PendingResponse::create(vm, request);
  825. pending_preflight_response->when_loaded([returned_pending_response, pending_actual_response, fetch_main_content = move(fetch_main_content)](JS::NonnullGCPtr<Infrastructure::Response> preflight_response) {
  826. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_preflight_response load callback");
  827. // 2. If preflightResponse is a network error, then return preflightResponse.
  828. if (preflight_response->is_network_error()) {
  829. returned_pending_response->resolve(preflight_response);
  830. return;
  831. }
  832. auto pending_main_content_response = TRY_OR_IGNORE(fetch_main_content());
  833. pending_main_content_response->when_loaded([pending_actual_response](JS::NonnullGCPtr<Infrastructure::Response> main_content_response) {
  834. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_main_content_response load callback");
  835. pending_actual_response->resolve(main_content_response);
  836. });
  837. });
  838. } else {
  839. pending_actual_response = TRY(fetch_main_content());
  840. }
  841. } else {
  842. pending_actual_response = PendingResponse::create(vm, request, Infrastructure::Response::create(vm));
  843. }
  844. pending_actual_response->when_loaded([&realm, &vm, &fetch_params, request, response, actual_response, returned_pending_response, response_was_null = !response](JS::NonnullGCPtr<Infrastructure::Response> resolved_actual_response) mutable {
  845. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' pending_actual_response load callback");
  846. if (response_was_null) {
  847. response = actual_response = resolved_actual_response;
  848. // 4. If request’s response tainting is "cors" and a CORS check for request and response returns failure,
  849. // then return a network error.
  850. // NOTE: As the CORS check is not to be applied to responses whose status is 304 or 407, or responses from
  851. // a service worker for that matter, it is applied here.
  852. if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS
  853. && !cors_check(request, *response)) {
  854. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "Request with 'cors' response tainting failed CORS check"_string));
  855. return;
  856. }
  857. // 5. If the TAO check for request and response returns failure, then set request’s timing allow failed flag.
  858. if (!tao_check(request, *response))
  859. request->set_timing_allow_failed(true);
  860. }
  861. // 6. If either request’s response tainting or response’s type is "opaque", and the cross-origin resource
  862. // policy check with request’s origin, request’s client, request’s destination, and actualResponse returns
  863. // blocked, then return a network error.
  864. // NOTE: The cross-origin resource policy check runs for responses coming from the network and responses coming
  865. // from the service worker. This is different from the CORS check, as request’s client and the service
  866. // worker can have different embedder policies.
  867. if ((request->response_tainting() == Infrastructure::Request::ResponseTainting::Opaque || response->type() == Infrastructure::Response::Type::Opaque)
  868. && false // FIXME: "and the cross-origin resource policy check with request’s origin, request’s client, request’s destination, and actualResponse returns blocked"
  869. ) {
  870. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "Response was blocked by cross-origin resource policy check"_string));
  871. return;
  872. }
  873. JS::GCPtr<PendingResponse> inner_pending_response;
  874. // 7. If actualResponse’s status is a redirect status, then:
  875. if (Infrastructure::is_redirect_status(actual_response->status())) {
  876. // FIXME: 1. If actualResponse’s status is not 303, request’s body is not null, and the connection uses HTTP/2,
  877. // then user agents may, and are even encouraged to, transmit an RST_STREAM frame.
  878. // NOTE: 303 is excluded as certain communities ascribe special status to it.
  879. // 2. Switch on request’s redirect mode:
  880. switch (request->redirect_mode()) {
  881. // -> "error"
  882. case Infrastructure::Request::RedirectMode::Error:
  883. // Set response to a network error.
  884. response = Infrastructure::Response::network_error(vm, "Request with 'error' redirect mode received redirect response"_string);
  885. break;
  886. // -> "manual"
  887. case Infrastructure::Request::RedirectMode::Manual:
  888. // 1. If request’s mode is "navigate", then set fetchParams’s controller’s next manual redirect steps
  889. // to run HTTP-redirect fetch given fetchParams and response.
  890. if (request->mode() == Infrastructure::Request::Mode::Navigate) {
  891. fetch_params.controller()->set_next_manual_redirect_steps([&realm, &fetch_params, response] {
  892. (void)http_redirect_fetch(realm, fetch_params, *response);
  893. });
  894. }
  895. // 2. Otherwise, set response to an opaque-redirect filtered response whose internal response is
  896. // actualResponse.
  897. else {
  898. response = Infrastructure::OpaqueRedirectFilteredResponse::create(vm, *actual_response);
  899. }
  900. break;
  901. // -> "follow"
  902. case Infrastructure::Request::RedirectMode::Follow:
  903. // Set response to the result of running HTTP-redirect fetch given fetchParams and response.
  904. inner_pending_response = TRY_OR_IGNORE(http_redirect_fetch(realm, fetch_params, *response));
  905. break;
  906. default:
  907. VERIFY_NOT_REACHED();
  908. }
  909. }
  910. if (inner_pending_response) {
  911. inner_pending_response->when_loaded([returned_pending_response](JS::NonnullGCPtr<Infrastructure::Response> response) {
  912. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP fetch' inner_pending_response load callback");
  913. returned_pending_response->resolve(response);
  914. });
  915. } else {
  916. returned_pending_response->resolve(*response);
  917. }
  918. });
  919. // 8. Return response.
  920. // NOTE: Typically actualResponse’s body’s stream is still being enqueued to after returning.
  921. return returned_pending_response;
  922. }
  923. // https://fetch.spec.whatwg.org/#concept-http-redirect-fetch
  924. WebIDL::ExceptionOr<JS::GCPtr<PendingResponse>> http_redirect_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, Infrastructure::Response& response)
  925. {
  926. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-redirect fetch' with: fetch_params @ {}, response = {}", &fetch_params, &response);
  927. auto& vm = realm.vm();
  928. // 1. Let request be fetchParams’s request.
  929. auto request = fetch_params.request();
  930. // 2. Let actualResponse be response, if response is not a filtered response, and response’s internal response
  931. // otherwise.
  932. auto actual_response = !is<Infrastructure::FilteredResponse>(response)
  933. ? JS::NonnullGCPtr { response }
  934. : static_cast<Infrastructure::FilteredResponse const&>(response).internal_response();
  935. // 3. Let locationURL be actualResponse’s location URL given request’s current URL’s fragment.
  936. auto location_url_or_error = actual_response->location_url(request->current_url().fragment());
  937. // 4. If locationURL is null, then return response.
  938. if (!location_url_or_error.is_error() && !location_url_or_error.value().has_value())
  939. return PendingResponse::create(vm, request, response);
  940. // 5. If locationURL is failure, then return a network error.
  941. if (location_url_or_error.is_error())
  942. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request redirect URL is invalid"sv));
  943. auto location_url = location_url_or_error.release_value().release_value();
  944. // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network error.
  945. if (!Infrastructure::is_http_or_https_scheme(location_url.scheme()))
  946. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request redirect URL must have HTTP or HTTPS scheme"sv));
  947. // 7. If request’s redirect count is 20, then return a network error.
  948. if (request->redirect_count() == 20)
  949. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has reached maximum redirect count of 20"sv));
  950. // 8. Increase request’s redirect count by 1.
  951. request->set_redirect_count(request->redirect_count() + 1);
  952. // 8. If request’s mode is "cors", locationURL includes credentials, and request’s origin is not same origin with
  953. // locationURL’s origin, then return a network error.
  954. if (request->mode() == Infrastructure::Request::Mode::CORS
  955. && location_url.includes_credentials()
  956. && request->origin().has<HTML::Origin>()
  957. && !request->origin().get<HTML::Origin>().is_same_origin(DOMURL::url_origin(location_url))) {
  958. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'cors' mode and different URL and request origin must not include credentials in redirect URL"sv));
  959. }
  960. // 10. If request’s response tainting is "cors" and locationURL includes credentials, then return a network error.
  961. // NOTE: This catches a cross-origin resource redirecting to a same-origin URL.
  962. if (request->response_tainting() == Infrastructure::Request::ResponseTainting::CORS && location_url.includes_credentials())
  963. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'cors' response tainting must not include credentials in redirect URL"sv));
  964. // 11. If actualResponse’s status is not 303, request’s body is non-null, and request’s body’s source is null, then
  965. // return a network error.
  966. if (actual_response->status() != 303
  967. && !request->body().has<Empty>()
  968. && request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source().has<Empty>()) {
  969. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request has body but no body source"sv));
  970. }
  971. // 12. If one of the following is true
  972. if (
  973. // - actualResponse’s status is 301 or 302 and request’s method is `POST`
  974. ((actual_response->status() == 301 || actual_response->status() == 302) && request->method() == "POST"sv.bytes())
  975. // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
  976. || (actual_response->status() == 303 && !(request->method() == "GET"sv.bytes() || request->method() == "HEAD"sv.bytes()))
  977. // then:
  978. ) {
  979. // 1. Set request’s method to `GET` and request’s body to null.
  980. request->set_method(MUST(ByteBuffer::copy("GET"sv.bytes())));
  981. request->set_body({});
  982. static constexpr Array request_body_header_names {
  983. "Content-Encoding"sv,
  984. "Content-Language"sv,
  985. "Content-Location"sv,
  986. "Content-Type"sv
  987. };
  988. // 2. For each headerName of request-body-header name, delete headerName from request’s header list.
  989. for (auto header_name : request_body_header_names.span())
  990. request->header_list()->delete_(header_name.bytes());
  991. }
  992. // 13. If request’s current URL’s origin is not same origin with locationURL’s origin, then for each headerName of
  993. // CORS non-wildcard request-header name, delete headerName from request’s header list.
  994. // NOTE: I.e., the moment another origin is seen after the initial request, the `Authorization` header is removed.
  995. if (!DOMURL::url_origin(request->current_url()).is_same_origin(DOMURL::url_origin(location_url))) {
  996. static constexpr Array cors_non_wildcard_request_header_names {
  997. "Authorization"sv
  998. };
  999. for (auto header_name : cors_non_wildcard_request_header_names)
  1000. request->header_list()->delete_(header_name.bytes());
  1001. }
  1002. // 14. If request’s body is non-null, then set request’s body to the body of the result of safely extracting
  1003. // request’s body’s source.
  1004. // NOTE: request’s body’s source’s nullity has already been checked.
  1005. if (!request->body().has<Empty>()) {
  1006. auto const& source = request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source();
  1007. // NOTE: BodyInitOrReadableBytes is a superset of Body::SourceType
  1008. auto converted_source = source.has<ByteBuffer>()
  1009. ? BodyInitOrReadableBytes { source.get<ByteBuffer>() }
  1010. : BodyInitOrReadableBytes { source.get<JS::Handle<FileAPI::Blob>>() };
  1011. auto [body, _] = TRY(safely_extract_body(realm, converted_source));
  1012. request->set_body(move(body));
  1013. }
  1014. // 15. Let timingInfo be fetchParams’s timing info.
  1015. auto timing_info = fetch_params.timing_info();
  1016. // 16. Set timingInfo’s redirect end time and post-redirect start time to the coarsened shared current time given
  1017. // fetchParams’s cross-origin isolated capability.
  1018. auto now = HighResolutionTime::coarsened_shared_current_time(fetch_params.cross_origin_isolated_capability() == HTML::CanUseCrossOriginIsolatedAPIs::Yes);
  1019. timing_info->set_redirect_end_time(now);
  1020. timing_info->set_post_redirect_start_time(now);
  1021. // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s redirect start time to timingInfo’s start
  1022. // time.
  1023. if (timing_info->redirect_start_time() == 0)
  1024. timing_info->set_redirect_start_time(timing_info->start_time());
  1025. // 18. Append locationURL to request’s URL list.
  1026. request->url_list().append(location_url);
  1027. // FIXME: 19. Invoke set request’s referrer policy on redirect on request and actualResponse.
  1028. // 20. Let recursive be true.
  1029. auto recursive = Recursive::Yes;
  1030. // 21. If request’s redirect mode is "manual", then:
  1031. if (request->redirect_mode() == Infrastructure::Request::RedirectMode::Manual) {
  1032. // 1. Assert: request’s mode is "navigate".
  1033. VERIFY(request->mode() == Infrastructure::Request::Mode::Navigate);
  1034. // 2. Set recursive to false.
  1035. recursive = Recursive::No;
  1036. }
  1037. // 22. Return the result of running main fetch given fetchParams and recursive.
  1038. return main_fetch(realm, fetch_params, recursive);
  1039. }
  1040. // https://fetch.spec.whatwg.org/#concept-http-network-or-cache-fetch
  1041. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> http_network_or_cache_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, IsAuthenticationFetch is_authentication_fetch, IsNewConnectionFetch is_new_connection_fetch)
  1042. {
  1043. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' with: fetch_params @ {}, is_authentication_fetch = {}, is_new_connection_fetch = {}",
  1044. &fetch_params, is_authentication_fetch == IsAuthenticationFetch::Yes ? "Yes"sv : "No"sv, is_new_connection_fetch == IsNewConnectionFetch::Yes ? "Yes"sv : "No"sv);
  1045. auto& vm = realm.vm();
  1046. // 1. Let request be fetchParams’s request.
  1047. auto request = fetch_params.request();
  1048. // 2. Let httpFetchParams be null.
  1049. JS::GCPtr<Infrastructure::FetchParams const> http_fetch_params;
  1050. // 3. Let httpRequest be null.
  1051. JS::GCPtr<Infrastructure::Request> http_request;
  1052. // 4. Let response be null.
  1053. JS::GCPtr<Infrastructure::Response> response;
  1054. // 5. Let storedResponse be null.
  1055. JS::GCPtr<Infrastructure::Response> stored_response;
  1056. // 6. Let httpCache be null.
  1057. // (Typeless until we actually implement it, needed for checks below)
  1058. void* http_cache = nullptr;
  1059. // 7. Let the revalidatingFlag be unset.
  1060. auto revalidating_flag = RefCountedFlag::create(false);
  1061. auto include_credentials = IncludeCredentials::No;
  1062. // 8. Run these steps, but abort when fetchParams is canceled:
  1063. // NOTE: There's an 'if aborted' check after this anyway, so not doing this is fine and only incurs a small delay.
  1064. // For now, support for aborting fetch requests is limited anyway as ResourceLoader doesn't support it.
  1065. auto aborted = false;
  1066. {
  1067. ScopeGuard set_aborted = [&] {
  1068. if (fetch_params.is_canceled())
  1069. aborted = true;
  1070. };
  1071. // 1. If request’s window is "no-window" and request’s redirect mode is "error", then set httpFetchParams to
  1072. // fetchParams and httpRequest to request.
  1073. if (request->window().has<Infrastructure::Request::Window>()
  1074. && request->window().get<Infrastructure::Request::Window>() == Infrastructure::Request::Window::NoWindow
  1075. && request->redirect_mode() == Infrastructure::Request::RedirectMode::Error) {
  1076. http_fetch_params = fetch_params;
  1077. http_request = request;
  1078. }
  1079. // 2. Otherwise:
  1080. else {
  1081. // 1. Set httpRequest to a clone of request.
  1082. // NOTE: Implementations are encouraged to avoid teeing request’s body’s stream when request’s body’s
  1083. // source is null as only a single body is needed in that case. E.g., when request’s body’s source
  1084. // is null, redirects and authentication will end up failing the fetch.
  1085. http_request = request->clone(realm);
  1086. // 2. Set httpFetchParams to a copy of fetchParams.
  1087. // 3. Set httpFetchParams’s request to httpRequest.
  1088. auto new_http_fetch_params = Infrastructure::FetchParams::create(vm, *http_request, fetch_params.timing_info());
  1089. new_http_fetch_params->set_algorithms(fetch_params.algorithms());
  1090. new_http_fetch_params->set_task_destination(fetch_params.task_destination());
  1091. new_http_fetch_params->set_cross_origin_isolated_capability(fetch_params.cross_origin_isolated_capability());
  1092. new_http_fetch_params->set_preloaded_response_candidate(fetch_params.preloaded_response_candidate());
  1093. http_fetch_params = new_http_fetch_params;
  1094. }
  1095. // 3. Let includeCredentials be true if one of
  1096. if (
  1097. // - request’s credentials mode is "include"
  1098. request->credentials_mode() == Infrastructure::Request::CredentialsMode::Include
  1099. // - request’s credentials mode is "same-origin" and request’s response tainting is "basic"
  1100. || (request->credentials_mode() == Infrastructure::Request::CredentialsMode::SameOrigin
  1101. && request->response_tainting() == Infrastructure::Request::ResponseTainting::Basic)
  1102. // is true; otherwise false.
  1103. ) {
  1104. include_credentials = IncludeCredentials::Yes;
  1105. } else {
  1106. include_credentials = IncludeCredentials::No;
  1107. }
  1108. // 4. If Cross-Origin-Embedder-Policy allows credentials with request returns false, then set
  1109. // includeCredentials to false.
  1110. if (!request->cross_origin_embedder_policy_allows_credentials())
  1111. include_credentials = IncludeCredentials::No;
  1112. // 5. Let contentLength be httpRequest’s body’s length, if httpRequest’s body is non-null; otherwise null.
  1113. auto content_length = http_request->body().has<JS::NonnullGCPtr<Infrastructure::Body>>()
  1114. ? http_request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->length()
  1115. : Optional<u64> {};
  1116. // 6. Let contentLengthHeaderValue be null.
  1117. auto content_length_header_value = Optional<ByteBuffer> {};
  1118. // 7. If httpRequest’s body is null and httpRequest’s method is `POST` or `PUT`, then set
  1119. // contentLengthHeaderValue to `0`.
  1120. if (http_request->body().has<Empty>() && StringView { http_request->method() }.is_one_of("POST"sv, "PUT"sv))
  1121. content_length_header_value = MUST(ByteBuffer::copy("0"sv.bytes()));
  1122. // 8. If contentLength is non-null, then set contentLengthHeaderValue to contentLength, serialized and
  1123. // isomorphic encoded.
  1124. if (content_length.has_value())
  1125. content_length_header_value = MUST(ByteBuffer::copy(TRY_OR_THROW_OOM(vm, String::number(*content_length)).bytes()));
  1126. // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, contentLengthHeaderValue) to
  1127. // httpRequest’s header list.
  1128. if (content_length_header_value.has_value()) {
  1129. auto header = Infrastructure::Header {
  1130. .name = MUST(ByteBuffer::copy("Content-Length"sv.bytes())),
  1131. .value = content_length_header_value.release_value(),
  1132. };
  1133. http_request->header_list()->append(move(header));
  1134. }
  1135. // FIXME: 10. If contentLength is non-null and httpRequest’s keepalive is true, then:
  1136. if (content_length.has_value() && http_request->keepalive()) {
  1137. // FIXME: 1-5., requires 'fetch records' and 'fetch group' concepts.
  1138. // NOTE: The above limit ensures that requests that are allowed to outlive the environment settings object
  1139. // and contain a body, have a bounded size and are not allowed to stay alive indefinitely.
  1140. }
  1141. // 11. If httpRequest’s referrer is a URL, then:
  1142. if (http_request->referrer().has<URL::URL>()) {
  1143. // 1. Let referrerValue be httpRequest’s referrer, serialized and isomorphic encoded.
  1144. auto referrer_string = http_request->referrer().get<URL::URL>().serialize();
  1145. auto referrer_value = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(referrer_string.bytes()));
  1146. // 2. Append (`Referer`, referrerValue) to httpRequest’s header list.
  1147. auto header = Infrastructure::Header {
  1148. .name = MUST(ByteBuffer::copy("Referer"sv.bytes())),
  1149. .value = move(referrer_value),
  1150. };
  1151. http_request->header_list()->append(move(header));
  1152. }
  1153. // 12. Append a request `Origin` header for httpRequest.
  1154. http_request->add_origin_header();
  1155. // FIXME: 13. Append the Fetch metadata headers for httpRequest.
  1156. // 14. If httpRequest’s header list does not contain `User-Agent`, then user agents should append
  1157. // (`User-Agent`, default `User-Agent` value) to httpRequest’s header list.
  1158. if (!http_request->header_list()->contains("User-Agent"sv.bytes())) {
  1159. auto header = Infrastructure::Header {
  1160. .name = MUST(ByteBuffer::copy("User-Agent"sv.bytes())),
  1161. .value = Infrastructure::default_user_agent_value(),
  1162. };
  1163. http_request->header_list()->append(move(header));
  1164. }
  1165. // 15. If httpRequest’s cache mode is "default" and httpRequest’s header list contains `If-Modified-Since`,
  1166. // `If-None-Match`, `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set httpRequest’s cache mode to
  1167. // "no-store".
  1168. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::Default
  1169. && (http_request->header_list()->contains("If-Modified-Since"sv.bytes())
  1170. || http_request->header_list()->contains("If-None-Match"sv.bytes())
  1171. || http_request->header_list()->contains("If-Unmodified-Since"sv.bytes())
  1172. || http_request->header_list()->contains("If-Match"sv.bytes())
  1173. || http_request->header_list()->contains("If-Range"sv.bytes()))) {
  1174. http_request->set_cache_mode(Infrastructure::Request::CacheMode::NoStore);
  1175. }
  1176. // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent no-cache cache-control header
  1177. // modification flag is unset, and httpRequest’s header list does not contain `Cache-Control`, then append
  1178. // (`Cache-Control`, `max-age=0`) to httpRequest’s header list.
  1179. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::NoCache
  1180. && !http_request->prevent_no_cache_cache_control_header_modification()
  1181. && !http_request->header_list()->contains("Cache-Control"sv.bytes())) {
  1182. auto header = Infrastructure::Header::from_string_pair("Cache-Control"sv, "max-age=0"sv);
  1183. http_request->header_list()->append(move(header));
  1184. }
  1185. // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
  1186. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::NoStore
  1187. || http_request->cache_mode() == Infrastructure::Request::CacheMode::Reload) {
  1188. // 1. If httpRequest’s header list does not contain `Pragma`, then append (`Pragma`, `no-cache`) to
  1189. // httpRequest’s header list.
  1190. if (!http_request->header_list()->contains("Pragma"sv.bytes())) {
  1191. auto header = Infrastructure::Header::from_string_pair("Pragma"sv, "no-cache"sv);
  1192. http_request->header_list()->append(move(header));
  1193. }
  1194. // 2. If httpRequest’s header list does not contain `Cache-Control`, then append
  1195. // (`Cache-Control`, `no-cache`) to httpRequest’s header list.
  1196. if (!http_request->header_list()->contains("Cache-Control"sv.bytes())) {
  1197. auto header = Infrastructure::Header::from_string_pair("Cache-Control"sv, "no-cache"sv);
  1198. http_request->header_list()->append(move(header));
  1199. }
  1200. }
  1201. // 18. If httpRequest’s header list contains `Range`, then append (`Accept-Encoding`, `identity`) to
  1202. // httpRequest’s header list.
  1203. // NOTE: This avoids a failure when handling content codings with a part of an encoded response.
  1204. // Additionally, many servers mistakenly ignore `Range` headers if a non-identity encoding is accepted.
  1205. if (http_request->header_list()->contains("Range"sv.bytes())) {
  1206. auto header = Infrastructure::Header::from_string_pair("Accept-Encoding"sv, "identity"sv);
  1207. http_request->header_list()->append(move(header));
  1208. }
  1209. // 19. Modify httpRequest’s header list per HTTP. Do not append a given header if httpRequest’s header list
  1210. // contains that header’s name.
  1211. // NOTE: It would be great if we could make this more normative somehow. At this point headers such as
  1212. // `Accept-Encoding`, `Connection`, `DNT`, and `Host`, are to be appended if necessary.
  1213. // `Accept`, `Accept-Charset`, and `Accept-Language` must not be included at this point.
  1214. // NOTE: `Accept` and `Accept-Language` are already included (unless fetch() is used, which does not include
  1215. // the latter by default), and `Accept-Charset` is a waste of bytes. See HTTP header layer division for
  1216. // more details.
  1217. // 20. If includeCredentials is true, then:
  1218. if (include_credentials == IncludeCredentials::Yes) {
  1219. // 1. If the user agent is not configured to block cookies for httpRequest (see section 7 of [COOKIES]),
  1220. // then:
  1221. if (true) {
  1222. // 1. Let cookies be the result of running the "cookie-string" algorithm (see section 5.4 of [COOKIES])
  1223. // with the user agent’s cookie store and httpRequest’s current URL.
  1224. auto cookies = ([&] {
  1225. // FIXME: Getting to the page client reliably is way too complicated, and going via the document won't work in workers.
  1226. auto document = Bindings::host_defined_environment_settings_object(realm).responsible_document();
  1227. if (!document)
  1228. return String {};
  1229. return document->page().client().page_did_request_cookie(http_request->current_url(), Cookie::Source::Http);
  1230. })();
  1231. // 2. If cookies is not the empty string, then append (`Cookie`, cookies) to httpRequest’s header list.
  1232. if (!cookies.is_empty()) {
  1233. auto header = Infrastructure::Header::from_string_pair("Cookie"sv, cookies);
  1234. http_request->header_list()->append(move(header));
  1235. }
  1236. }
  1237. // 2. If httpRequest’s header list does not contain `Authorization`, then:
  1238. if (!http_request->header_list()->contains("Authorization"sv.bytes())) {
  1239. // 1. Let authorizationValue be null.
  1240. auto authorization_value = Optional<String> {};
  1241. // 2. If there’s an authentication entry for httpRequest and either httpRequest’s use-URL-credentials
  1242. // flag is unset or httpRequest’s current URL does not include credentials, then set
  1243. // authorizationValue to authentication entry.
  1244. if (false // FIXME: "If there’s an authentication entry for httpRequest"
  1245. && (!http_request->use_url_credentials() || !http_request->current_url().includes_credentials())) {
  1246. // FIXME: "set authorizationValue to authentication entry."
  1247. }
  1248. // 3. Otherwise, if httpRequest’s current URL does include credentials and isAuthenticationFetch is
  1249. // true, set authorizationValue to httpRequest’s current URL, converted to an `Authorization` value.
  1250. else if (http_request->current_url().includes_credentials() && is_authentication_fetch == IsAuthenticationFetch::Yes) {
  1251. auto const& url = http_request->current_url();
  1252. auto payload = MUST(String::formatted("{}:{}", MUST(url.username()), MUST(url.password())));
  1253. authorization_value = TRY_OR_THROW_OOM(vm, encode_base64(payload.bytes()));
  1254. }
  1255. // 4. If authorizationValue is non-null, then append (`Authorization`, authorizationValue) to
  1256. // httpRequest’s header list.
  1257. if (authorization_value.has_value()) {
  1258. auto header = Infrastructure::Header::from_string_pair("Authorization"sv, *authorization_value);
  1259. http_request->header_list()->append(move(header));
  1260. }
  1261. }
  1262. }
  1263. // FIXME: 21. If there’s a proxy-authentication entry, use it as appropriate.
  1264. // NOTE: This intentionally does not depend on httpRequest’s credentials mode.
  1265. // FIXME: 22. Set httpCache to the result of determining the HTTP cache partition, given httpRequest.
  1266. // 23. If httpCache is null, then set httpRequest’s cache mode to "no-store".
  1267. if (!http_cache)
  1268. http_request->set_cache_mode(Infrastructure::Request::CacheMode::NoStore);
  1269. // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", then:
  1270. if (http_request->cache_mode() != Infrastructure::Request::CacheMode::NoStore
  1271. && http_request->cache_mode() != Infrastructure::Request::CacheMode::Reload) {
  1272. // 1. Set storedResponse to the result of selecting a response from the httpCache, possibly needing
  1273. // validation, as per the "Constructing Responses from Caches" chapter of HTTP Caching [HTTP-CACHING],
  1274. // if any.
  1275. // NOTE: As mandated by HTTP, this still takes the `Vary` header into account.
  1276. stored_response = nullptr;
  1277. // 2. If storedResponse is non-null, then:
  1278. if (stored_response) {
  1279. // FIXME: Caching is not implemented yet.
  1280. VERIFY_NOT_REACHED();
  1281. }
  1282. }
  1283. }
  1284. // 9. If aborted, then return the appropriate network error for fetchParams.
  1285. if (aborted)
  1286. return PendingResponse::create(vm, request, Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1287. JS::GCPtr<PendingResponse> pending_forward_response;
  1288. // 10. If response is null, then:
  1289. if (!response) {
  1290. // 1. If httpRequest’s cache mode is "only-if-cached", then return a network error.
  1291. if (http_request->cache_mode() == Infrastructure::Request::CacheMode::OnlyIfCached)
  1292. return PendingResponse::create(vm, request, Infrastructure::Response::network_error(vm, "Request with 'only-if-cached' cache mode doesn't have a cached response"sv));
  1293. // 2. Let forwardResponse be the result of running HTTP-network fetch given httpFetchParams, includeCredentials,
  1294. // and isNewConnectionFetch.
  1295. pending_forward_response = TRY(nonstandard_resource_loader_file_or_http_network_fetch(realm, *http_fetch_params, include_credentials, is_new_connection_fetch));
  1296. } else {
  1297. pending_forward_response = PendingResponse::create(vm, request, Infrastructure::Response::create(vm));
  1298. }
  1299. auto returned_pending_response = PendingResponse::create(vm, request);
  1300. pending_forward_response->when_loaded([&realm, &vm, &fetch_params, request, response, stored_response, http_request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch, revalidating_flag, include_credentials, response_was_null = !response](JS::NonnullGCPtr<Infrastructure::Response> resolved_forward_response) mutable {
  1301. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP-network-or-cache fetch' pending_forward_response load callback");
  1302. if (response_was_null) {
  1303. auto forward_response = resolved_forward_response;
  1304. // NOTE: TRACE is omitted as it is a forbidden method in Fetch.
  1305. auto method_is_unsafe = StringView { http_request->method() }.is_one_of("GET"sv, "HEAD"sv, "OPTIONS"sv);
  1306. // 3. If httpRequest’s method is unsafe and forwardResponse’s status is in the range 200 to 399, inclusive,
  1307. // invalidate appropriate stored responses in httpCache, as per the "Invalidation" chapter of HTTP
  1308. // Caching, and set storedResponse to null.
  1309. if (method_is_unsafe && forward_response->status() >= 200 && forward_response->status() <= 399) {
  1310. // FIXME: "invalidate appropriate stored responses in httpCache, as per the "Invalidation" chapter of HTTP Caching"
  1311. stored_response = nullptr;
  1312. }
  1313. // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, then:
  1314. if (revalidating_flag->value() && forward_response->status() == 304) {
  1315. // FIXME: 1. Update storedResponse’s header list using forwardResponse’s header list, as per the "Freshening
  1316. // Stored Responses upon Validation" chapter of HTTP Caching.
  1317. // NOTE: This updates the stored response in cache as well.
  1318. // 2. Set response to storedResponse.
  1319. response = stored_response;
  1320. // 3. Set response’s cache state to "validated".
  1321. if (response)
  1322. response->set_cache_state(Infrastructure::Response::CacheState::Validated);
  1323. }
  1324. // 5. If response is null, then:
  1325. if (!response) {
  1326. // 1. Set response to forwardResponse.
  1327. response = forward_response;
  1328. // FIXME: 2. Store httpRequest and forwardResponse in httpCache, as per the "Storing Responses in Caches"
  1329. // chapter of HTTP Caching.
  1330. // NOTE: If forwardResponse is a network error, this effectively caches the network error, which is
  1331. // sometimes known as "negative caching".
  1332. // NOTE: The associated body info is stored in the cache alongside the response.
  1333. }
  1334. }
  1335. // 11. Set response’s URL list to a clone of httpRequest’s URL list.
  1336. response->set_url_list(http_request->url_list());
  1337. // 12. If httpRequest’s header list contains `Range`, then set response’s range-requested flag.
  1338. if (http_request->header_list()->contains("Range"sv.bytes()))
  1339. response->set_range_requested(true);
  1340. // 13. Set response’s request-includes-credentials to includeCredentials.
  1341. response->set_request_includes_credentials(include_credentials == IncludeCredentials::Yes);
  1342. auto inner_pending_response = PendingResponse::create(vm, request, *response);
  1343. // 14. If response’s status is 401, httpRequest’s response tainting is not "cors", includeCredentials is true,
  1344. // and request’s window is an environment settings object, then:
  1345. if (response->status() == 401
  1346. && http_request->response_tainting() != Infrastructure::Request::ResponseTainting::CORS
  1347. && include_credentials == IncludeCredentials::Yes
  1348. && request->window().has<JS::GCPtr<HTML::EnvironmentSettingsObject>>()) {
  1349. // 1. Needs testing: multiple `WWW-Authenticate` headers, missing, parsing issues.
  1350. // (Red box in the spec, no-op)
  1351. // 2. If request’s body is non-null, then:
  1352. if (!request->body().has<Empty>()) {
  1353. // 1. If request’s body’s source is null, then return a network error.
  1354. if (request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source().has<Empty>()) {
  1355. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "Request has body but no body source"_string));
  1356. return;
  1357. }
  1358. // 2. Set request’s body to the body of the result of safely extracting request’s body’s source.
  1359. auto const& source = request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source();
  1360. // NOTE: BodyInitOrReadableBytes is a superset of Body::SourceType
  1361. auto converted_source = source.has<ByteBuffer>()
  1362. ? BodyInitOrReadableBytes { source.get<ByteBuffer>() }
  1363. : BodyInitOrReadableBytes { source.get<JS::Handle<FileAPI::Blob>>() };
  1364. auto [body, _] = TRY_OR_IGNORE(safely_extract_body(realm, converted_source));
  1365. request->set_body(move(body));
  1366. }
  1367. // 3. If request’s use-URL-credentials flag is unset or isAuthenticationFetch is true, then:
  1368. if (!request->use_url_credentials() || is_authentication_fetch == IsAuthenticationFetch::Yes) {
  1369. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1370. if (fetch_params.is_canceled()) {
  1371. returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1372. return;
  1373. }
  1374. // FIXME: 2. Let username and password be the result of prompting the end user for a username and password,
  1375. // respectively, in request’s window.
  1376. dbgln("Fetch: Username/password prompt is not implemented, using empty strings. This request will probably fail.");
  1377. auto username = ByteString::empty();
  1378. auto password = ByteString::empty();
  1379. // 3. Set the username given request’s current URL and username.
  1380. MUST(request->current_url().set_username(username));
  1381. // 4. Set the password given request’s current URL and password.
  1382. MUST(request->current_url().set_password(password));
  1383. }
  1384. // 4. Set response to the result of running HTTP-network-or-cache fetch given fetchParams and true.
  1385. inner_pending_response = TRY_OR_IGNORE(http_network_or_cache_fetch(realm, fetch_params, IsAuthenticationFetch::Yes));
  1386. }
  1387. inner_pending_response->when_loaded([&realm, &vm, &fetch_params, request, returned_pending_response, is_authentication_fetch, is_new_connection_fetch](JS::NonnullGCPtr<Infrastructure::Response> response) {
  1388. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'HTTP network-or-cache fetch' inner_pending_response load callback");
  1389. // 15. If response’s status is 407, then:
  1390. if (response->status() == 407) {
  1391. // 1. If request’s window is "no-window", then return a network error.
  1392. if (request->window().has<Infrastructure::Request::Window>()
  1393. && request->window().get<Infrastructure::Request::Window>() == Infrastructure::Request::Window::NoWindow) {
  1394. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "Request requires proxy authentication but has 'no-window' set"_string));
  1395. return;
  1396. }
  1397. // 2. Needs testing: multiple `Proxy-Authenticate` headers, missing, parsing issues.
  1398. // (Red box in the spec, no-op)
  1399. // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1400. if (fetch_params.is_canceled()) {
  1401. returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1402. return;
  1403. }
  1404. // FIXME: 4. Prompt the end user as appropriate in request’s window and store the result as a
  1405. // proxy-authentication entry.
  1406. // NOTE: Remaining details surrounding proxy authentication are defined by HTTP.
  1407. // FIXME: 5. Set response to the result of running HTTP-network-or-cache fetch given fetchParams.
  1408. // (Doing this without step 4 would potentially lead to an infinite request cycle.)
  1409. }
  1410. auto inner_pending_response = PendingResponse::create(vm, request, *response);
  1411. // 16. If all of the following are true
  1412. if (
  1413. // - response’s status is 421
  1414. response->status() == 421
  1415. // - isNewConnectionFetch is false
  1416. && is_new_connection_fetch == IsNewConnectionFetch::No
  1417. // - request’s body is null, or request’s body is non-null and request’s body’s source is non-null
  1418. && (request->body().has<Empty>() || !request->body().get<JS::NonnullGCPtr<Infrastructure::Body>>()->source().has<Empty>())
  1419. // then:
  1420. ) {
  1421. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1422. if (fetch_params.is_canceled()) {
  1423. returned_pending_response->resolve(Infrastructure::Response::appropriate_network_error(vm, fetch_params));
  1424. return;
  1425. }
  1426. // 2. Set response to the result of running HTTP-network-or-cache fetch given fetchParams,
  1427. // isAuthenticationFetch, and true.
  1428. inner_pending_response = TRY_OR_IGNORE(http_network_or_cache_fetch(realm, fetch_params, is_authentication_fetch, IsNewConnectionFetch::Yes));
  1429. }
  1430. inner_pending_response->when_loaded([returned_pending_response, is_authentication_fetch](JS::NonnullGCPtr<Infrastructure::Response> response) {
  1431. // 17. If isAuthenticationFetch is true, then create an authentication entry for request and the given
  1432. // realm.
  1433. if (is_authentication_fetch == IsAuthenticationFetch::Yes) {
  1434. // FIXME: "create an authentication entry for request and the given realm"
  1435. }
  1436. returned_pending_response->resolve(response);
  1437. });
  1438. });
  1439. });
  1440. // 18. Return response.
  1441. // NOTE: Typically response’s body’s stream is still being enqueued to after returning.
  1442. return returned_pending_response;
  1443. }
  1444. #if defined(WEB_FETCH_DEBUG)
  1445. static void log_load_request(auto const& load_request)
  1446. {
  1447. dbgln("Fetch: Invoking ResourceLoader");
  1448. dbgln("> {} {} HTTP/1.1", load_request.method(), load_request.url());
  1449. for (auto const& [name, value] : load_request.headers())
  1450. dbgln("> {}: {}", name, value);
  1451. dbgln(">");
  1452. for (auto line : StringView { load_request.body() }.split_view('\n', SplitBehavior::KeepEmpty))
  1453. dbgln("> {}", line);
  1454. }
  1455. static void log_response(auto const& status_code, auto const& headers, auto const& data)
  1456. {
  1457. dbgln("< HTTP/1.1 {}", status_code.value_or(0));
  1458. for (auto const& [name, value] : headers)
  1459. dbgln("< {}: {}", name, value);
  1460. dbgln("<");
  1461. for (auto line : StringView { data }.split_view('\n', SplitBehavior::KeepEmpty))
  1462. dbgln("< {}", line);
  1463. }
  1464. #endif
  1465. // https://fetch.spec.whatwg.org/#concept-http-network-fetch
  1466. // Drop-in replacement for 'HTTP-network fetch', but obviously non-standard :^)
  1467. // It also handles file:// URLs since those can also go through ResourceLoader.
  1468. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> nonstandard_resource_loader_file_or_http_network_fetch(JS::Realm& realm, Infrastructure::FetchParams const& fetch_params, IncludeCredentials include_credentials, IsNewConnectionFetch is_new_connection_fetch)
  1469. {
  1470. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'non-standard HTTP-network fetch' with: fetch_params @ {}", &fetch_params);
  1471. auto& vm = realm.vm();
  1472. (void)include_credentials;
  1473. (void)is_new_connection_fetch;
  1474. auto request = fetch_params.request();
  1475. auto& page = Bindings::host_defined_page(realm);
  1476. // NOTE: Using LoadRequest::create_for_url_on_page here will unconditionally add cookies as long as there's a page available.
  1477. // However, it is up to http_network_or_cache_fetch to determine if cookies should be added to the request.
  1478. LoadRequest load_request;
  1479. load_request.set_url(request->current_url());
  1480. load_request.set_page(page);
  1481. load_request.set_method(ByteString::copy(request->method()));
  1482. for (auto const& header : *request->header_list())
  1483. load_request.set_header(ByteString::copy(header.name), ByteString::copy(header.value));
  1484. if (auto const* body = request->body().get_pointer<JS::NonnullGCPtr<Infrastructure::Body>>()) {
  1485. TRY((*body)->source().visit(
  1486. [&](ByteBuffer const& byte_buffer) -> WebIDL::ExceptionOr<void> {
  1487. load_request.set_body(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(byte_buffer)));
  1488. return {};
  1489. },
  1490. [&](JS::Handle<FileAPI::Blob> const& blob_handle) -> WebIDL::ExceptionOr<void> {
  1491. load_request.set_body(TRY_OR_THROW_OOM(vm, ByteBuffer::copy(blob_handle->bytes())));
  1492. return {};
  1493. },
  1494. [](Empty) -> WebIDL::ExceptionOr<void> {
  1495. return {};
  1496. }));
  1497. }
  1498. auto pending_response = PendingResponse::create(vm, request);
  1499. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Invoking ResourceLoader");
  1500. if constexpr (WEB_FETCH_DEBUG)
  1501. log_load_request(load_request);
  1502. ResourceLoader::the().load(
  1503. load_request,
  1504. [&realm, &vm, request, pending_response](auto data, auto& response_headers, auto status_code) {
  1505. dbgln_if(WEB_FETCH_DEBUG, "Fetch: ResourceLoader load for '{}' complete", request->url());
  1506. if constexpr (WEB_FETCH_DEBUG)
  1507. log_response(status_code, response_headers, data);
  1508. auto [body, _] = TRY_OR_IGNORE(extract_body(realm, data));
  1509. auto response = Infrastructure::Response::create(vm);
  1510. response->set_status(status_code.value_or(200));
  1511. response->set_body(move(body));
  1512. for (auto const& [name, value] : response_headers) {
  1513. auto header = Infrastructure::Header::from_string_pair(name, value);
  1514. response->header_list()->append(move(header));
  1515. }
  1516. // FIXME: Set response status message
  1517. pending_response->resolve(response);
  1518. },
  1519. [&realm, &vm, request, pending_response](auto& error, auto status_code, auto data, auto& response_headers) {
  1520. dbgln_if(WEB_FETCH_DEBUG, "Fetch: ResourceLoader load for '{}' failed: {} (status {})", request->url(), error, status_code.value_or(0));
  1521. if constexpr (WEB_FETCH_DEBUG)
  1522. log_response(status_code, response_headers, data);
  1523. auto response = Infrastructure::Response::create(vm);
  1524. // FIXME: This is ugly, ResourceLoader should tell us.
  1525. if (status_code.value_or(0) == 0) {
  1526. response = Infrastructure::Response::network_error(vm, "HTTP request failed"_string);
  1527. } else {
  1528. response->set_type(Infrastructure::Response::Type::Error);
  1529. response->set_status(status_code.value_or(400));
  1530. auto [body, _] = TRY_OR_IGNORE(extract_body(realm, data));
  1531. response->set_body(move(body));
  1532. for (auto const& [name, value] : response_headers) {
  1533. auto header = Infrastructure::Header::from_string_pair(name, value);
  1534. response->header_list()->append(move(header));
  1535. }
  1536. // FIXME: Set response status message
  1537. }
  1538. pending_response->resolve(response);
  1539. });
  1540. return pending_response;
  1541. }
  1542. // https://fetch.spec.whatwg.org/#cors-preflight-fetch-0
  1543. WebIDL::ExceptionOr<JS::NonnullGCPtr<PendingResponse>> cors_preflight_fetch(JS::Realm& realm, Infrastructure::Request& request)
  1544. {
  1545. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' with request @ {}", &request);
  1546. auto& vm = realm.vm();
  1547. // 1. Let preflight be a new request whose method is `OPTIONS`, URL list is a clone of request’s URL list, initiator is
  1548. // request’s initiator, destination is request’s destination, origin is request’s origin, referrer is request’s referrer,
  1549. // referrer policy is request’s referrer policy, mode is "cors", and response tainting is "cors".
  1550. auto preflight = Fetch::Infrastructure::Request::create(vm);
  1551. preflight->set_method(TRY_OR_THROW_OOM(vm, ByteBuffer::copy("OPTIONS"sv.bytes())));
  1552. preflight->set_url_list(request.url_list());
  1553. preflight->set_initiator(request.initiator());
  1554. preflight->set_destination(request.destination());
  1555. preflight->set_origin(request.origin());
  1556. preflight->set_referrer(request.referrer());
  1557. preflight->set_referrer_policy(request.referrer_policy());
  1558. preflight->set_mode(Infrastructure::Request::Mode::CORS);
  1559. preflight->set_response_tainting(Infrastructure::Request::ResponseTainting::CORS);
  1560. // 2. Append (`Accept`, `*/*`) to preflight’s header list.
  1561. auto temp_header = Infrastructure::Header::from_string_pair("Accept"sv, "*/*"sv);
  1562. preflight->header_list()->append(move(temp_header));
  1563. // 3. Append (`Access-Control-Request-Method`, request’s method) to preflight’s header list.
  1564. temp_header = Infrastructure::Header::from_string_pair("Access-Control-Request-Method"sv, request.method());
  1565. preflight->header_list()->append(move(temp_header));
  1566. // 4. Let headers be the CORS-unsafe request-header names with request’s header list.
  1567. auto headers = Infrastructure::get_cors_unsafe_header_names(request.header_list());
  1568. // 5. If headers is not empty, then:
  1569. if (!headers.is_empty()) {
  1570. // 1. Let value be the items in headers separated from each other by `,`.
  1571. // NOTE: This intentionally does not use combine, as 0x20 following 0x2C is not the way this was implemented,
  1572. // for better or worse.
  1573. ByteBuffer value;
  1574. bool first = true;
  1575. for (auto const& header : headers) {
  1576. if (!first)
  1577. TRY_OR_THROW_OOM(vm, value.try_append(','));
  1578. TRY_OR_THROW_OOM(vm, value.try_append(header));
  1579. first = false;
  1580. }
  1581. // 2. Append (`Access-Control-Request-Headers`, value) to preflight’s header list.
  1582. temp_header = Infrastructure::Header {
  1583. .name = TRY_OR_THROW_OOM(vm, ByteBuffer::copy("Access-Control-Request-Headers"sv.bytes())),
  1584. .value = move(value),
  1585. };
  1586. preflight->header_list()->append(move(temp_header));
  1587. }
  1588. // 6. Let response be the result of running HTTP-network-or-cache fetch given a new fetch params whose request is preflight.
  1589. // FIXME: The spec doesn't say anything about timing_info here, but FetchParams requires a non-null FetchTimingInfo object.
  1590. auto timing_info = Infrastructure::FetchTimingInfo::create(vm);
  1591. auto fetch_params = Infrastructure::FetchParams::create(vm, preflight, timing_info);
  1592. auto returned_pending_response = PendingResponse::create(vm, request);
  1593. auto preflight_response = TRY(http_network_or_cache_fetch(realm, fetch_params));
  1594. preflight_response->when_loaded([&vm, &request, returned_pending_response](JS::NonnullGCPtr<Infrastructure::Response> response) {
  1595. dbgln_if(WEB_FETCH_DEBUG, "Fetch: Running 'CORS-preflight fetch' preflight_response load callback");
  1596. // 7. If a CORS check for request and response returns success and response’s status is an ok status, then:
  1597. // NOTE: The CORS check is done on request rather than preflight to ensure the correct credentials mode is used.
  1598. if (cors_check(request, response) && Infrastructure::is_ok_status(response->status())) {
  1599. // 1. Let methods be the result of extracting header list values given `Access-Control-Allow-Methods` and response’s header list.
  1600. auto methods_or_failure = Infrastructure::extract_header_list_values("Access-Control-Allow-Methods"sv.bytes(), response->header_list());
  1601. // 2. Let headerNames be the result of extracting header list values given `Access-Control-Allow-Headers` and
  1602. // response’s header list.
  1603. auto header_names_or_failure = Infrastructure::extract_header_list_values("Access-Control-Allow-Headers"sv.bytes(), response->header_list());
  1604. // 3. If either methods or headerNames is failure, return a network error.
  1605. if (methods_or_failure.has<Infrastructure::ExtractHeaderParseFailure>()) {
  1606. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "The Access-Control-Allow-Methods in the CORS-preflight response is syntactically invalid"_string));
  1607. return;
  1608. }
  1609. if (header_names_or_failure.has<Infrastructure::ExtractHeaderParseFailure>()) {
  1610. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "The Access-Control-Allow-Headers in the CORS-preflight response is syntactically invalid"_string));
  1611. return;
  1612. }
  1613. // NOTE: We treat "methods_or_failure" being `Empty` as empty Vector here.
  1614. auto methods = methods_or_failure.has<Vector<ByteBuffer>>() ? methods_or_failure.get<Vector<ByteBuffer>>() : Vector<ByteBuffer> {};
  1615. // NOTE: We treat "header_names_or_failure" being `Empty` as empty Vector here.
  1616. auto header_names = header_names_or_failure.has<Vector<ByteBuffer>>() ? header_names_or_failure.get<Vector<ByteBuffer>>() : Vector<ByteBuffer> {};
  1617. // 4. If methods is null and request’s use-CORS-preflight flag is set, then set methods to a new list containing request’s method.
  1618. // NOTE: This ensures that a CORS-preflight fetch that happened due to request’s use-CORS-preflight flag being set is cached.
  1619. if (methods.is_empty() && request.use_cors_preflight())
  1620. methods = Vector { TRY_OR_IGNORE(ByteBuffer::copy(request.method())) };
  1621. // 5. If request’s method is not in methods, request’s method is not a CORS-safelisted method, and request’s credentials mode
  1622. // is "include" or methods does not contain `*`, then return a network error.
  1623. if (!methods.contains_slow(request.method()) && !Infrastructure::is_cors_safelisted_method(request.method())) {
  1624. if (request.credentials_mode() == Infrastructure::Request::CredentialsMode::Include) {
  1625. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE(String::formatted("Non-CORS-safelisted method '{}' not found in the CORS-preflight response's Access-Control-Allow-Methods header (the header may be missing). '*' is not allowed as the main request includes credentials."sv, StringView { request.method() }))));
  1626. return;
  1627. }
  1628. if (!methods.contains_slow("*"sv.bytes())) {
  1629. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE(String::formatted("Non-CORS-safelisted method '{}' not found in the CORS-preflight response's Access-Control-Allow-Methods header and there was no '*' entry. The header may be missing."sv, StringView { request.method() }))));
  1630. return;
  1631. }
  1632. }
  1633. // 6. If one of request’s header list’s names is a CORS non-wildcard request-header name and is not a byte-case-insensitive match
  1634. // for an item in headerNames, then return a network error.
  1635. for (auto const& header : *request.header_list()) {
  1636. if (Infrastructure::is_cors_non_wildcard_request_header_name(header.name)) {
  1637. bool is_in_header_names = false;
  1638. for (auto const& allowed_header_name : header_names) {
  1639. if (StringView { allowed_header_name }.equals_ignoring_ascii_case(header.name)) {
  1640. is_in_header_names = true;
  1641. break;
  1642. }
  1643. }
  1644. if (!is_in_header_names) {
  1645. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE(String::formatted("Main request contains the header '{}' that is not specified in the CORS-preflight response's Access-Control-Allow-Headers header (the header may be missing). '*' does not capture this header."sv, StringView { header.name }))));
  1646. return;
  1647. }
  1648. }
  1649. }
  1650. // 7. For each unsafeName of the CORS-unsafe request-header names with request’s header list, if unsafeName is not a
  1651. // byte-case-insensitive match for an item in headerNames and request’s credentials mode is "include" or headerNames
  1652. // does not contain `*`, return a network error.
  1653. auto unsafe_names = Infrastructure::get_cors_unsafe_header_names(request.header_list());
  1654. for (auto const& unsafe_name : unsafe_names) {
  1655. bool is_in_header_names = false;
  1656. for (auto const& header_name : header_names) {
  1657. if (StringView { unsafe_name }.equals_ignoring_ascii_case(header_name)) {
  1658. is_in_header_names = true;
  1659. break;
  1660. }
  1661. }
  1662. if (!is_in_header_names) {
  1663. if (request.credentials_mode() == Infrastructure::Request::CredentialsMode::Include) {
  1664. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE(String::formatted("CORS-unsafe request-header '{}' not found in the CORS-preflight response's Access-Control-Allow-Headers header (the header may be missing). '*' is not allowed as the main request includes credentials."sv, StringView { unsafe_name }))));
  1665. return;
  1666. }
  1667. if (!header_names.contains_slow("*"sv.bytes())) {
  1668. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, TRY_OR_IGNORE(String::formatted("CORS-unsafe request-header '{}' not found in the CORS-preflight response's Access-Control-Allow-Headers header and there was no '*' entry. The header may be missing."sv, StringView { unsafe_name }))));
  1669. return;
  1670. }
  1671. }
  1672. }
  1673. // FIXME: 8. Let max-age be the result of extracting header list values given `Access-Control-Max-Age` and response’s header list.
  1674. // FIXME: 9. If max-age is failure or null, then set max-age to 5.
  1675. // FIXME: 10. If max-age is greater than an imposed limit on max-age, then set max-age to the imposed limit.
  1676. // 11. If the user agent does not provide for a cache, then return response.
  1677. // NOTE: Since we don't currently have a cache, this is always true.
  1678. returned_pending_response->resolve(response);
  1679. return;
  1680. // FIXME: 12. For each method in methods for which there is a method cache entry match using request, set matching entry’s max-age
  1681. // to max-age.
  1682. // FIXME: 13. For each method in methods for which there is no method cache entry match using request, create a new cache entry
  1683. // with request, max-age, method, and null.
  1684. // FIXME: 14. For each headerName in headerNames for which there is a header-name cache entry match using request, set matching
  1685. // entry’s max-age to max-age.
  1686. // FIXME: 15. For each headerName in headerNames for which there is no header-name cache entry match using request, create a
  1687. // new cache entry with request, max-age, null, and headerName.
  1688. // FIXME: 16. Return response.
  1689. }
  1690. // 8. Otherwise, return a network error.
  1691. returned_pending_response->resolve(Infrastructure::Response::network_error(vm, "CORS-preflight check failed"_string));
  1692. });
  1693. return returned_pending_response;
  1694. }
  1695. // https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-dest
  1696. void set_sec_fetch_dest_header(Infrastructure::Request& request)
  1697. {
  1698. // 1. Assert: r’s url is a potentially trustworthy URL.
  1699. VERIFY(SecureContexts::is_url_potentially_trustworthy(request.url()) == SecureContexts::Trustworthiness::PotentiallyTrustworthy);
  1700. // 2. Let header be a Structured Header whose value is a token.
  1701. // FIXME: This is handled below, as Serenity doesn't have APIs for RFC 8941.
  1702. // 3. If r’s destination is the empty string, set header’s value to the string "empty". Otherwise, set header’s value to r’s destination.
  1703. ByteBuffer header_value;
  1704. if (!request.destination().has_value()) {
  1705. header_value = MUST(ByteBuffer::copy("empty"sv.bytes()));
  1706. } else {
  1707. header_value = MUST(ByteBuffer::copy(Infrastructure::request_destination_to_string(request.destination().value()).bytes()));
  1708. }
  1709. // 4. Set a structured field value `Sec-Fetch-Dest`/header in r’s header list.
  1710. auto header = Infrastructure::Header {
  1711. .name = MUST(ByteBuffer::copy("Sec-Fetch-Dest"sv.bytes())),
  1712. .value = move(header_value),
  1713. };
  1714. request.header_list()->append(move(header));
  1715. }
  1716. // https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-dest
  1717. void set_sec_fetch_mode_header(Infrastructure::Request& request)
  1718. {
  1719. // 1. Assert: r’s url is a potentially trustworthy URL.
  1720. VERIFY(SecureContexts::is_url_potentially_trustworthy(request.url()) == SecureContexts::Trustworthiness::PotentiallyTrustworthy);
  1721. // 2. Let header be a Structured Header whose value is a token.
  1722. // FIXME: This is handled below, as Serenity doesn't have APIs for RFC 8941.
  1723. // 3. Set header’s value to r’s mode.
  1724. auto header_value = MUST(ByteBuffer::copy(Infrastructure::request_mode_to_string(request.mode()).bytes()));
  1725. // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
  1726. auto header = Infrastructure::Header {
  1727. .name = MUST(ByteBuffer::copy("Sec-Fetch-Mode"sv.bytes())),
  1728. .value = move(header_value),
  1729. };
  1730. request.header_list()->append(move(header));
  1731. }
  1732. // https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-site
  1733. void set_sec_fetch_site_header(Infrastructure::Request& request)
  1734. {
  1735. // 1. Assert: r’s url is a potentially trustworthy URL.
  1736. VERIFY(SecureContexts::is_url_potentially_trustworthy(request.url()) == SecureContexts::Trustworthiness::PotentiallyTrustworthy);
  1737. // 2. Let header be a Structured Header whose value is a token.
  1738. // FIXME: This is handled below, as Serenity doesn't have APIs for RFC 8941.
  1739. // 3. Set header’s value to same-origin.
  1740. auto header_value = "same-origin"sv;
  1741. // FIXME: 4. If r is a navigation request that was explicitly caused by a user’s interaction with the user agent (by typing an address
  1742. // into the user agent directly, for example, or by clicking a bookmark, etc.), then set header’s value to none.
  1743. // 5. If header’s value is not none, then for each url in r’s url list:
  1744. if (!header_value.equals_ignoring_ascii_case("none"sv)) {
  1745. for (auto& url : request.url_list()) {
  1746. // 1. If url is same origin with r’s origin, continue.
  1747. if (DOMURL::url_origin(url).is_same_origin(DOMURL::url_origin(request.current_url())))
  1748. continue;
  1749. // 2. Set header’s value to cross-site.
  1750. header_value = "cross-site"sv;
  1751. // FIXME: 3. If r’s origin is not same site with url’s origin, then break.
  1752. // FIXME: 4. Set header’s value to same-site.
  1753. }
  1754. }
  1755. // 6. Set a structured field value `Sec-Fetch-Site`/header in r’s header list.
  1756. auto header = Infrastructure::Header {
  1757. .name = MUST(ByteBuffer::copy("Sec-Fetch-Site"sv.bytes())),
  1758. .value = MUST(ByteBuffer::copy(header_value.bytes())),
  1759. };
  1760. request.header_list()->append(move(header));
  1761. }
  1762. // https://w3c.github.io/webappsec-fetch-metadata/#abstract-opdef-set-user
  1763. void set_sec_fetch_user_header(Infrastructure::Request& request)
  1764. {
  1765. // 1. Assert: r’s url is a potentially trustworthy URL.
  1766. VERIFY(SecureContexts::is_url_potentially_trustworthy(request.url()) == SecureContexts::Trustworthiness::PotentiallyTrustworthy);
  1767. // 2. If r is not a navigation request, or if r’s user-activation is false, return.
  1768. if (!request.is_navigation_request() || !request.user_activation())
  1769. return;
  1770. // 3. Let header be a Structured Header whose value is a token.
  1771. // FIXME: This is handled below, as Serenity doesn't have APIs for RFC 8941.
  1772. // 4. Set header’s value to true.
  1773. // NOTE: See https://datatracker.ietf.org/doc/html/rfc8941#name-booleans for boolean format in RFC 8941.
  1774. auto header_value = MUST(ByteBuffer::copy("?1"sv.bytes()));
  1775. // 5. Set a structured field value `Sec-Fetch-User`/header in r’s header list.
  1776. auto header = Infrastructure::Header {
  1777. .name = MUST(ByteBuffer::copy("Sec-Fetch-User"sv.bytes())),
  1778. .value = move(header_value),
  1779. };
  1780. request.header_list()->append(move(header));
  1781. }
  1782. }