Coverage Report

Created: 2026-11-13 08:07

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