Headers.cpp 13 KB

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