Coverage Report

Created: 2025-09-05 06:52

/src/serenity/Userland/Libraries/LibWeb/Fetch/Response.cpp
Line
Count
Source (jump to first uncovered line)
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 <LibWeb/Bindings/Intrinsics.h>
9
#include <LibWeb/Bindings/MainThreadVM.h>
10
#include <LibWeb/Bindings/ResponsePrototype.h>
11
#include <LibWeb/DOMURL/DOMURL.h>
12
#include <LibWeb/Fetch/Enums.h>
13
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
14
#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
15
#include <LibWeb/Fetch/Infrastructure/HTTP/Statuses.h>
16
#include <LibWeb/Fetch/Response.h>
17
#include <LibWeb/HTML/Scripting/Environments.h>
18
#include <LibWeb/Infra/JSON.h>
19
20
namespace Web::Fetch {
21
22
JS_DEFINE_ALLOCATOR(Response);
23
24
Response::Response(JS::Realm& realm, JS::NonnullGCPtr<Infrastructure::Response> response)
25
0
    : PlatformObject(realm)
26
0
    , m_response(response)
27
0
{
28
0
}
29
30
0
Response::~Response() = default;
31
32
void Response::initialize(JS::Realm& realm)
33
0
{
34
0
    Base::initialize(realm);
35
0
    WEB_SET_PROTOTYPE_FOR_INTERFACE(Response);
36
0
}
37
38
void Response::visit_edges(Cell::Visitor& visitor)
39
0
{
40
0
    Base::visit_edges(visitor);
41
0
    visitor.visit(m_response);
42
0
    visitor.visit(m_headers);
43
0
}
44
45
// https://fetch.spec.whatwg.org/#concept-body-mime-type
46
// https://fetch.spec.whatwg.org/#ref-for-concept-header-extract-mime-type%E2%91%A7
47
Optional<MimeSniff::MimeType> Response::mime_type_impl() const
48
0
{
49
    // Objects including the Body interface mixin need to define an associated MIME type algorithm which takes no arguments and returns failure or a MIME type.
50
    // A Response object’s MIME type is to return the result of extracting a MIME type from its response’s header list.
51
0
    return m_response->header_list()->extract_mime_type();
52
0
}
53
54
// https://fetch.spec.whatwg.org/#concept-body-body
55
// https://fetch.spec.whatwg.org/#ref-for-concept-body-body%E2%91%A8
56
JS::GCPtr<Infrastructure::Body const> Response::body_impl() const
57
0
{
58
    // Objects including the Body interface mixin have an associated body (null or a body).
59
    // A Response object’s body is its response’s body.
60
0
    return m_response->body() ? m_response->body() : nullptr;
61
0
}
62
63
// https://fetch.spec.whatwg.org/#concept-body-body
64
// https://fetch.spec.whatwg.org/#ref-for-concept-body-body%E2%91%A8
65
JS::GCPtr<Infrastructure::Body> Response::body_impl()
66
0
{
67
    // Objects including the Body interface mixin have an associated body (null or a body).
68
    // A Response object’s body is its response’s body.
69
0
    return m_response->body() ? m_response->body() : nullptr;
70
0
}
71
72
// https://fetch.spec.whatwg.org/#response-create
73
JS::NonnullGCPtr<Response> Response::create(JS::Realm& realm, JS::NonnullGCPtr<Infrastructure::Response> response, Headers::Guard guard)
74
0
{
75
    // 1. Let responseObject be a new Response object with realm.
76
    // 2. Set responseObject’s response to response.
77
0
    auto response_object = realm.heap().allocate<Response>(realm, realm, response);
78
79
    // 3. Set responseObject’s headers to a new Headers object with realm, whose headers list is response’s headers list and guard is guard.
80
0
    response_object->m_headers = realm.heap().allocate<Headers>(realm, realm, response->header_list());
81
0
    response_object->m_headers->set_guard(guard);
82
83
    // 4. Return responseObject.
84
0
    return response_object;
85
0
}
86
87
// https://fetch.spec.whatwg.org/#initialize-a-response
88
WebIDL::ExceptionOr<void> Response::initialize_response(ResponseInit const& init, Optional<Infrastructure::BodyWithType> const& body)
89
0
{
90
    // 1. If init["status"] is not in the range 200 to 599, inclusive, then throw a RangeError.
91
0
    if (init.status < 200 || init.status > 599)
92
0
        return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Status must be in range 200-599"sv };
93
94
    // FIXME: 2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
95
96
    // 3. Set response’s response’s status to init["status"].
97
0
    m_response->set_status(init.status);
98
99
    // 4. Set response’s response’s status message to init["statusText"].
100
0
    m_response->set_status_message(MUST(ByteBuffer::copy(init.status_text.bytes())));
101
102
    // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
103
0
    if (init.headers.has_value())
104
0
        TRY(m_headers->fill(*init.headers));
105
106
    // 6. If body was given, then:
107
0
    if (body.has_value()) {
108
        // 1. If response’s status is a null body status, then throw a TypeError.
109
0
        if (Infrastructure::is_null_body_status(m_response->status()))
110
0
            return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Response with null body status cannot have a body"sv };
111
112
        // 2. Set response’s body to body’s body.
113
0
        m_response->set_body(body->body);
114
115
        // 3. If body’s type is non-null and response’s header list does not contain `Content-Type`, then append (`Content-Type`, body’s type) to response’s header list.
116
0
        if (body->type.has_value() && !m_response->header_list()->contains("Content-Type"sv.bytes())) {
117
0
            auto header = Infrastructure::Header {
118
0
                .name = MUST(ByteBuffer::copy("Content-Type"sv.bytes())),
119
0
                .value = MUST(ByteBuffer::copy(body->type->span())),
120
0
            };
121
0
            m_response->header_list()->append(move(header));
122
0
        }
123
0
    }
124
125
0
    return {};
126
0
}
127
128
// https://fetch.spec.whatwg.org/#dom-response
129
WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::construct_impl(JS::Realm& realm, Optional<BodyInit> const& body, ResponseInit const& init)
130
0
{
131
0
    auto& vm = realm.vm();
132
133
    // Referred to as 'this' in the spec.
134
0
    auto response_object = realm.heap().allocate<Response>(realm, realm, Infrastructure::Response::create(vm));
135
136
    // 1. Set this’s response to a new response.
137
    // NOTE: This is done at the beginning as the 'this' value Response object
138
    //       cannot exist with a null Infrastructure::Response.
139
140
    // 2. Set this’s headers to a new Headers object with this’s relevant Realm, whose header list is this’s response’s header list and guard is "response".
141
0
    response_object->m_headers = realm.heap().allocate<Headers>(realm, realm, response_object->response()->header_list());
142
0
    response_object->m_headers->set_guard(Headers::Guard::Response);
143
144
    // 3. Let bodyWithType be null.
145
0
    Optional<Infrastructure::BodyWithType> body_with_type;
146
147
    // 4. If body is non-null, then set bodyWithType to the result of extracting body.
148
0
    if (body.has_value())
149
0
        body_with_type = TRY(extract_body(realm, *body));
150
151
    // 5. Perform initialize a response given this, init, and bodyWithType.
152
0
    TRY(response_object->initialize_response(init, body_with_type));
153
154
0
    return response_object;
155
0
}
156
157
// https://fetch.spec.whatwg.org/#dom-response-error
158
JS::NonnullGCPtr<Response> Response::error(JS::VM& vm)
159
0
{
160
    // The static error() method steps are to return the result of creating a Response object, given a new network error, "immutable", and this’s relevant Realm.
161
    // FIXME: How can we reliably get 'this', i.e. the object the function was called on, in IDL-defined functions?
162
0
    return Response::create(*vm.current_realm(), Infrastructure::Response::network_error(vm, "Response created via `Response.error()`"sv), Headers::Guard::Immutable);
163
0
}
164
165
// https://fetch.spec.whatwg.org/#dom-response-redirect
166
WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::redirect(JS::VM& vm, String const& url, u16 status)
167
0
{
168
0
    auto& realm = *vm.current_realm();
169
170
    // 1. Let parsedURL be the result of parsing url with current settings object’s API base URL.
171
0
    auto api_base_url = HTML::current_settings_object().api_base_url();
172
0
    auto parsed_url = DOMURL::parse(url, api_base_url);
173
174
    // 2. If parsedURL is failure, then throw a TypeError.
175
0
    if (!parsed_url.is_valid())
176
0
        return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Redirect URL is not valid"sv };
177
178
    // 3. If status is not a redirect status, then throw a RangeError.
179
0
    if (!Infrastructure::is_redirect_status(status))
180
0
        return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Status must be one of 301, 302, 303, 307, or 308"sv };
181
182
    // 4. Let responseObject be the result of creating a Response object, given a new response, "immutable", and this’s relevant Realm.
183
    // FIXME: How can we reliably get 'this', i.e. the object the function was called on, in IDL-defined functions?
184
0
    auto response_object = Response::create(realm, Infrastructure::Response::create(vm), Headers::Guard::Immutable);
185
186
    // 5. Set responseObject’s response’s status to status.
187
0
    response_object->response()->set_status(status);
188
189
    // 6. Let value be parsedURL, serialized and isomorphic encoded.
190
0
    auto value = parsed_url.serialize();
191
192
    // 7. Append (`Location`, value) to responseObject’s response’s header list.
193
0
    auto header = Infrastructure::Header::from_string_pair("Location"sv, value);
194
0
    response_object->response()->header_list()->append(move(header));
195
196
    // 8. Return responseObject.
197
0
    return response_object;
198
0
}
199
200
// https://fetch.spec.whatwg.org/#dom-response-json
201
WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::json(JS::VM& vm, JS::Value data, ResponseInit const& init)
202
0
{
203
0
    auto& realm = *vm.current_realm();
204
205
    // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
206
0
    auto bytes = TRY(Infra::serialize_javascript_value_to_json_bytes(vm, data));
207
208
    // 2. Let body be the result of extracting bytes.
209
0
    auto [body, _] = TRY(extract_body(realm, { bytes.bytes() }));
210
211
    // 3. Let responseObject be the result of creating a Response object, given a new response, "response", and this’s relevant Realm.
212
    // FIXME: How can we reliably get 'this', i.e. the object the function was called on, in IDL-defined functions?
213
0
    auto response_object = Response::create(realm, Infrastructure::Response::create(vm), Headers::Guard::Response);
214
215
    // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
216
0
    auto body_with_type = Infrastructure::BodyWithType {
217
0
        .body = body,
218
0
        .type = MUST(ByteBuffer::copy("application/json"sv.bytes()))
219
0
    };
220
0
    TRY(response_object->initialize_response(init, move(body_with_type)));
221
222
    // 5. Return responseObject.
223
0
    return response_object;
224
0
}
225
226
// https://fetch.spec.whatwg.org/#dom-response-type
227
Bindings::ResponseType Response::type() const
228
0
{
229
    // The type getter steps are to return this’s response’s type.
230
0
    return to_bindings_enum(m_response->type());
231
0
}
232
233
// https://fetch.spec.whatwg.org/#dom-response-url
234
String Response::url() const
235
0
{
236
    // The url getter steps are to return the empty string if this’s response’s URL is null; otherwise this’s response’s URL, serialized with exclude fragment set to true.
237
0
    return !m_response->url().has_value()
238
0
        ? String {}
239
0
        : MUST(String::from_byte_string(m_response->url()->serialize(URL::ExcludeFragment::Yes)));
240
0
}
241
242
// https://fetch.spec.whatwg.org/#dom-response-redirected
243
bool Response::redirected() const
244
0
{
245
    // The redirected getter steps are to return true if this’s response’s URL list has more than one item; otherwise false.
246
0
    return m_response->url_list().size() > 1;
247
0
}
248
249
// https://fetch.spec.whatwg.org/#dom-response-status
250
u16 Response::status() const
251
0
{
252
    // The status getter steps are to return this’s response’s status.
253
0
    return m_response->status();
254
0
}
255
256
// https://fetch.spec.whatwg.org/#dom-response-ok
257
bool Response::ok() const
258
0
{
259
    // The ok getter steps are to return true if this’s response’s status is an ok status; otherwise false.
260
0
    return Infrastructure::is_ok_status(m_response->status());
261
0
}
262
263
// https://fetch.spec.whatwg.org/#dom-response-statustext
264
String Response::status_text() const
265
0
{
266
    // The statusText getter steps are to return this’s response’s status message.
267
0
    return MUST(String::from_utf8(m_response->status_message()));
268
0
}
269
270
// https://fetch.spec.whatwg.org/#dom-response-headers
271
JS::NonnullGCPtr<Headers> Response::headers() const
272
0
{
273
    // The headers getter steps are to return this’s headers.
274
0
    return *m_headers;
275
0
}
276
277
// https://fetch.spec.whatwg.org/#dom-response-clone
278
WebIDL::ExceptionOr<JS::NonnullGCPtr<Response>> Response::clone() const
279
0
{
280
0
    auto& realm = this->realm();
281
282
    // 1. If this is unusable, then throw a TypeError.
283
0
    if (is_unusable())
284
0
        return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Response is unusable"sv };
285
286
    // 2. Let clonedResponse be the result of cloning this’s response.
287
0
    auto cloned_response = m_response->clone(realm);
288
289
    // 3. Return the result of creating a Response object, given clonedResponse, this’s headers’s guard, and this’s relevant Realm.
290
0
    return Response::create(HTML::relevant_realm(*this), cloned_response, m_headers->guard());
291
0
}
292
293
}