Headers.cpp 12 KB

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