Headers.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/Completion.h>
  7. #include <LibJS/Runtime/VM.h>
  8. #include <LibWeb/Bindings/Intrinsics.h>
  9. #include <LibWeb/Fetch/Headers.h>
  10. namespace Web::Fetch {
  11. // https://fetch.spec.whatwg.org/#dom-headers
  12. WebIDL::ExceptionOr<JS::NonnullGCPtr<Headers>> Headers::construct_impl(JS::Realm& realm, Optional<HeadersInit> const& init)
  13. {
  14. auto& vm = realm.vm();
  15. // The new Headers(init) constructor steps are:
  16. auto headers = MUST_OR_THROW_OOM(realm.heap().allocate<Headers>(realm, realm, Infrastructure::HeaderList::create(vm)));
  17. // 1. Set this’s guard to "none".
  18. headers->m_guard = Guard::None;
  19. // 2. If init is given, then fill this with init.
  20. if (init.has_value())
  21. TRY(headers->fill(*init));
  22. return headers;
  23. }
  24. Headers::Headers(JS::Realm& realm, JS::NonnullGCPtr<Infrastructure::HeaderList> header_list)
  25. : PlatformObject(realm)
  26. , m_header_list(header_list)
  27. {
  28. }
  29. Headers::~Headers() = default;
  30. JS::ThrowCompletionOr<void> Headers::initialize(JS::Realm& realm)
  31. {
  32. MUST_OR_THROW_OOM(Base::initialize(realm));
  33. set_prototype(&Bindings::ensure_web_prototype<Bindings::HeadersPrototype>(realm, "Headers"));
  34. return {};
  35. }
  36. void Headers::visit_edges(JS::Cell::Visitor& visitor)
  37. {
  38. Base::visit_edges(visitor);
  39. visitor.visit(m_header_list);
  40. }
  41. // https://fetch.spec.whatwg.org/#dom-headers-append
  42. WebIDL::ExceptionOr<void> Headers::append(String const& name_string, String const& value_string)
  43. {
  44. auto& vm = this->vm();
  45. // The append(name, value) method steps are to append (name, value) to this.
  46. auto header = Infrastructure::Header {
  47. .name = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(name_string.bytes())),
  48. .value = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(value_string.bytes())),
  49. };
  50. TRY(append(move(header)));
  51. return {};
  52. }
  53. // https://fetch.spec.whatwg.org/#dom-headers-delete
  54. WebIDL::ExceptionOr<void> Headers::delete_(String const& name_string)
  55. {
  56. // The delete(name) method steps are:
  57. auto& vm = this->vm();
  58. auto name = name_string.bytes();
  59. // 1. If validating (name, ``) for headers returns false, then return.
  60. // NOTE: Passing a dummy header value ought not to have any negative repercussions.
  61. auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair(name, ""sv));
  62. if (!TRY(validate(header)))
  63. return {};
  64. // 2. If this’s guard is "request-no-cors", name is not a no-CORS-safelisted request-header name, and name is not a privileged no-CORS request-header name, then return.
  65. if (m_guard == Guard::RequestNoCORS && !Infrastructure::is_no_cors_safelisted_request_header_name(name) && !Infrastructure::is_privileged_no_cors_request_header_name(name))
  66. return {};
  67. // 3. If this’s header list does not contain name, then return.
  68. if (!m_header_list->contains(name))
  69. return {};
  70. // 4. Delete name from this’s header list.
  71. m_header_list->delete_(name);
  72. // 5. If this’s guard is "request-no-cors", then remove privileged no-CORS request-headers from this.
  73. if (m_guard == Guard::RequestNoCORS)
  74. remove_privileged_no_cors_request_headers();
  75. return {};
  76. }
  77. // https://fetch.spec.whatwg.org/#dom-headers-get
  78. WebIDL::ExceptionOr<Optional<String>> Headers::get(String const& name_string)
  79. {
  80. // The get(name) method steps are:
  81. auto& vm = this->vm();
  82. auto name = name_string.bytes();
  83. // 1. If name is not a header name, then throw a TypeError.
  84. if (!Infrastructure::is_header_name(name))
  85. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid header name"sv };
  86. // 2. Return the result of getting name from this’s header list.
  87. auto byte_buffer = TRY_OR_THROW_OOM(vm, m_header_list->get(name));
  88. return byte_buffer.has_value() ? TRY_OR_THROW_OOM(vm, String::from_utf8(*byte_buffer)) : Optional<String> {};
  89. }
  90. // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
  91. WebIDL::ExceptionOr<Vector<String>> Headers::get_set_cookie()
  92. {
  93. // The getSetCookie() method steps are:
  94. auto& vm = this->vm();
  95. auto values = Vector<String> {};
  96. // 1. If this’s header list does not contain `Set-Cookie`, then return « ».
  97. if (!m_header_list->contains("Set-Cookie"sv.bytes()))
  98. return values;
  99. // 2. Return the values of all headers in this’s header list whose name is a byte-case-insensitive match for
  100. // `Set-Cookie`, in order.
  101. for (auto const& header : *m_header_list) {
  102. if (StringView { header.name }.equals_ignoring_ascii_case("Set-Cookie"sv))
  103. TRY_OR_THROW_OOM(vm, values.try_append(TRY_OR_THROW_OOM(vm, String::from_utf8(header.value))));
  104. }
  105. return values;
  106. }
  107. // https://fetch.spec.whatwg.org/#dom-headers-has
  108. WebIDL::ExceptionOr<bool> Headers::has(String const& name_string)
  109. {
  110. // The has(name) method steps are:
  111. auto name = name_string.bytes();
  112. // 1. If name is not a header name, then throw a TypeError.
  113. if (!Infrastructure::is_header_name(name))
  114. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid header name"sv };
  115. // 2. Return true if this’s header list contains name; otherwise false.
  116. return m_header_list->contains(name);
  117. }
  118. // https://fetch.spec.whatwg.org/#dom-headers-set
  119. WebIDL::ExceptionOr<void> Headers::set(String const& name_string, String const& value_string)
  120. {
  121. auto& realm = this->realm();
  122. auto& vm = realm.vm();
  123. // The set(name, value) method steps are:
  124. auto name = name_string.bytes();
  125. auto value = value_string.bytes();
  126. // 1. Normalize value.
  127. auto normalized_value = TRY_OR_THROW_OOM(vm, Infrastructure::normalize_header_value(value));
  128. auto header = Infrastructure::Header {
  129. .name = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(name)),
  130. .value = move(normalized_value),
  131. };
  132. // 2. If validating (name, value) for headers returns false, then return.
  133. if (!TRY(validate(header)))
  134. return {};
  135. // 3. If this’s guard is "request-no-cors" and (name, value) is not a no-CORS-safelisted request-header, then return.
  136. if (m_guard == Guard::RequestNoCORS && !Infrastructure::is_no_cors_safelisted_request_header(header))
  137. return {};
  138. // 4. Set (name, value) in this’s header list.
  139. TRY_OR_THROW_OOM(vm, m_header_list->set(move(header)));
  140. // 5. If this’s guard is "request-no-cors", then remove privileged no-CORS request-headers from this.
  141. if (m_guard == Guard::RequestNoCORS)
  142. remove_privileged_no_cors_request_headers();
  143. return {};
  144. }
  145. // https://webidl.spec.whatwg.org/#es-iterable, Step 4
  146. JS::ThrowCompletionOr<void> Headers::for_each(ForEachCallback callback)
  147. {
  148. auto& vm = this->vm();
  149. // The value pairs to iterate over are the return value of running sort and combine with this’s header list.
  150. auto value_pairs_to_iterate_over = [&]() -> JS::ThrowCompletionOr<Vector<Fetch::Infrastructure::Header>> {
  151. return TRY_OR_THROW_OOM(vm, m_header_list->sort_and_combine());
  152. };
  153. // 1-5. Are done in the generated wrapper code.
  154. // 6. Let pairs be idlObject’s list of value pairs to iterate over.
  155. auto pairs = TRY(value_pairs_to_iterate_over());
  156. // 7. Let i be 0.
  157. size_t i = 0;
  158. // 8. While i < pairs’s size:
  159. while (i < pairs.size()) {
  160. // 1. Let pair be pairs[i].
  161. auto const& pair = pairs[i];
  162. // 2. Invoke idlCallback with « pair’s value, pair’s key, idlObject » and with thisArg as the callback this value.
  163. TRY(callback(TRY_OR_THROW_OOM(vm, String::from_utf8(pair.name)), TRY_OR_THROW_OOM(vm, String::from_utf8(pair.value))));
  164. // 3. Set pairs to idlObject’s current list of value pairs to iterate over. (It might have changed.)
  165. pairs = TRY(value_pairs_to_iterate_over());
  166. // 4. Set i to i + 1.
  167. ++i;
  168. }
  169. return {};
  170. }
  171. // https://fetch.spec.whatwg.org/#headers-validate
  172. WebIDL::ExceptionOr<bool> Headers::validate(Infrastructure::Header const& header) const
  173. {
  174. auto& realm = this->realm();
  175. // To validate a header (name, value) for a Headers object headers:
  176. auto const& [name, value] = header;
  177. // 1. If name is not a header name or value is not a header value, then throw a TypeError.
  178. if (!Infrastructure::is_header_name(name))
  179. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid header name"sv };
  180. if (!Infrastructure::is_header_value(value))
  181. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid header value"sv };
  182. // 2. If headers’s guard is "immutable", then throw a TypeError.
  183. if (m_guard == Guard::Immutable)
  184. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Headers object is immutable"sv };
  185. // 3. If headers’s guard is "request" and (name, value) is a forbidden request-header, then return false.
  186. if (m_guard == Guard::Request && TRY_OR_THROW_OOM(realm.vm(), Infrastructure::is_forbidden_request_header(header)))
  187. return false;
  188. // 4. If headers’s guard is "response" and name is a forbidden response-header name, then return false.
  189. if (m_guard == Guard::Response && Infrastructure::is_forbidden_response_header_name(name))
  190. return false;
  191. // 5. Return true.
  192. return true;
  193. }
  194. // https://fetch.spec.whatwg.org/#concept-headers-append
  195. WebIDL::ExceptionOr<void> Headers::append(Infrastructure::Header header)
  196. {
  197. auto& realm = this->realm();
  198. auto& vm = realm.vm();
  199. // To append a header (name, value) to a Headers object headers, run these steps:
  200. auto& [name, value] = header;
  201. // 1. Normalize value.
  202. value = TRY_OR_THROW_OOM(vm, Infrastructure::normalize_header_value(value));
  203. // 2. If validating (name, value) for headers returns false, then return.
  204. if (!TRY(validate(header)))
  205. return {};
  206. // 3. If headers’s guard is "request-no-cors":
  207. if (m_guard == Guard::RequestNoCORS) {
  208. // 1. Let temporaryValue be the result of getting name from headers’s header list.
  209. auto temporary_value = TRY_OR_THROW_OOM(vm, m_header_list->get(name));
  210. // 2. If temporaryValue is null, then set temporaryValue to value.
  211. if (!temporary_value.has_value()) {
  212. temporary_value = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(value));
  213. }
  214. // 3. Otherwise, set temporaryValue to temporaryValue, followed by 0x2C 0x20, followed by value.
  215. else {
  216. TRY_OR_THROW_OOM(vm, temporary_value->try_append(0x2c));
  217. TRY_OR_THROW_OOM(vm, temporary_value->try_append(0x20));
  218. TRY_OR_THROW_OOM(vm, temporary_value->try_append(value));
  219. }
  220. auto temporary_header = Infrastructure::Header {
  221. .name = TRY_OR_THROW_OOM(vm, ByteBuffer::copy(name)),
  222. .value = temporary_value.release_value(),
  223. };
  224. // 4. If (name, temporaryValue) is not a no-CORS-safelisted request-header, then return.
  225. if (!Infrastructure::is_no_cors_safelisted_request_header(temporary_header))
  226. return {};
  227. }
  228. // 4. Append (name, value) to headers’s header list.
  229. TRY_OR_THROW_OOM(vm, m_header_list->append(move(header)));
  230. // 5. If headers’s guard is "request-no-cors", then remove privileged no-CORS request-headers from headers.
  231. if (m_guard == Guard::RequestNoCORS)
  232. remove_privileged_no_cors_request_headers();
  233. return {};
  234. }
  235. // https://fetch.spec.whatwg.org/#concept-headers-fill
  236. WebIDL::ExceptionOr<void> Headers::fill(HeadersInit const& object)
  237. {
  238. auto& vm = realm().vm();
  239. // To fill a Headers object headers with a given object object, run these steps:
  240. return object.visit(
  241. // 1. If object is a sequence, then for each header of object:
  242. [&](Vector<Vector<String>> const& object) -> WebIDL::ExceptionOr<void> {
  243. for (auto const& entry : object) {
  244. // 1. If header's size is not 2, then throw a TypeError.
  245. if (entry.size() != 2)
  246. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Array must contain header key/value pair"sv };
  247. // 2. Append (header[0], header[1]) to headers.
  248. auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair(entry[0], entry[1]));
  249. TRY(append(move(header)));
  250. }
  251. return {};
  252. },
  253. // 2. Otherwise, object is a record, then for each key → value of object, append (key, value) to headers.
  254. [&](OrderedHashMap<String, String> const& object) -> WebIDL::ExceptionOr<void> {
  255. for (auto const& entry : object) {
  256. auto header = TRY_OR_THROW_OOM(vm, Infrastructure::Header::from_string_pair(entry.key, entry.value));
  257. TRY(append(move(header)));
  258. }
  259. return {};
  260. });
  261. }
  262. // https://fetch.spec.whatwg.org/#concept-headers-remove-privileged-no-cors-request-headers
  263. void Headers::remove_privileged_no_cors_request_headers()
  264. {
  265. // To remove privileged no-CORS request-headers from a Headers object (headers), run these steps:
  266. static constexpr Array privileged_no_cors_request_header_names = {
  267. "Range"sv,
  268. };
  269. // 1. For each headerName of privileged no-CORS request-header names:
  270. for (auto const& header_name : privileged_no_cors_request_header_names) {
  271. // 1. Delete headerName from headers’s header list.
  272. m_header_list->delete_(header_name.bytes());
  273. }
  274. }
  275. }