summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/fetch/headers.cc
blob: 3f4291baad295e20e8e7e34f7daf60d6eb051f49 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/core/fetch/headers.h"

#include "third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_union_bytestringbytestringrecord_bytestringsequencesequence.h"
#include "third_party/blink/renderer/core/dom/iterator.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/loader/cors/cors.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_utils.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"

namespace blink {

namespace {

class HeadersIterationSource final
    : public PairIterable<String, IDLString, String, IDLString>::
          IterationSource {
 public:
  explicit HeadersIterationSource(const FetchHeaderList* headers)
      : headers_(headers->SortAndCombine()), current_(0) {}

  bool Next(ScriptState* script_state,
            String& key,
            String& value,
            ExceptionState& exception) override {
    // This simply advances an index and returns the next value if any; the
    // iterated list is not exposed to script so it will never be mutated
    // during iteration.
    if (current_ >= headers_.size())
      return false;

    const FetchHeaderList::Header& header = headers_.at(current_++);
    key = header.first;
    value = header.second;
    return true;
  }

 private:
  Vector<std::pair<String, String>> headers_;
  wtf_size_t current_;
};

}  // namespace

Headers* Headers::Create(ScriptState* script_state, ExceptionState&) {
  return MakeGarbageCollected<Headers>();
}

Headers* Headers::Create(ScriptState* script_state,
                         const V8HeadersInit* init,
                         ExceptionState& exception_state) {
  // "The Headers(|init|) constructor, when invoked, must run these steps:"
  // "1. Let |headers| be a new Headers object whose guard is "none".
  Headers* headers = Create(script_state, exception_state);
  // "2. If |init| is given, fill headers with |init|. Rethrow any exception."
  headers->FillWith(script_state, init, exception_state);
  // "3. Return |headers|."
  return headers;
}

Headers* Headers::Create(FetchHeaderList* header_list) {
  return MakeGarbageCollected<Headers>(header_list);
}

Headers* Headers::Clone() const {
  FetchHeaderList* header_list = header_list_->Clone();
  Headers* headers = Create(header_list);
  headers->guard_ = guard_;
  return headers;
}

void Headers::append(ScriptState* script_state,
                     const String& name,
                     const String& value,
                     ExceptionState& exception_state) {
  // "To append a name/value (|name|/|value|) pair to a Headers object
  // (|headers|), run these steps:"
  // "1. Normalize |value|."
  const String normalized_value = FetchUtils::NormalizeHeaderValue(value);
  // "2. If |name| is not a name or |value| is not a value, throw a
  //     TypeError."
  if (!FetchHeaderList::IsValidHeaderName(name)) {
    exception_state.ThrowTypeError("Invalid name");
    return;
  }
  if (!FetchHeaderList::IsValidHeaderValue(normalized_value)) {
    exception_state.ThrowTypeError("Invalid value");
    return;
  }
  // "3. If guard is |immutable|, throw a TypeError."
  if (guard_ == kImmutableGuard) {
    exception_state.ThrowTypeError("Headers are immutable");
    return;
  }
  // UseCounter for usages of "set-cookie" in kRequestGuard'ed Headers.
  if (guard_ == kRequestGuard && name.LowerASCII() == "set-cookie") {
    ExecutionContext* execution_context = ExecutionContext::From(script_state);
    UseCounter::Count(execution_context,
                      WebFeature::kFetchSetCookieInRequestGuardedHeaders);
  }
  // "4. Otherwise, if guard is |request| and |name| is a forbidden header
  //     name, return."
  if (guard_ == kRequestGuard && cors::IsForbiddenHeaderName(name))
    return;
  // 5. Otherwise, if guard is |request-no-cors|:
  if (guard_ == kRequestNoCorsGuard) {
    // Let |temporaryValue| be the result of getting name from |headers|’s
    // header list.
    String temp;
    header_list_->Get(name, temp);

    // If |temporaryValue| is null, then set |temporaryValue| to |value|.
    // Otherwise, set |temporaryValue| to |temporaryValue|, followed by
    // 0x2C 0x20, followed by |value|.
    if (temp.IsNull()) {
      temp = normalized_value;
    } else {
      temp = temp + ", " + normalized_value;
    }

    // If |name|/|temporaryValue| is not a no-CORS-safelisted request-header,
    // then return.
    if (!cors::IsNoCorsSafelistedHeader(name, temp))
      return;
  }
  // "6. Otherwise, if guard is |response| and |name| is a forbidden response
  //     header name, return."
  if (guard_ == kResponseGuard &&
      FetchUtils::IsForbiddenResponseHeaderName(name)) {
    return;
  }
  // "7. Append |name|/|value| to header list."
  header_list_->Append(name, normalized_value);
  // "8. If this’s guard is |request-no-cors|, then remove privileged no-CORS
  // request headers from this."
  if (guard_ == kRequestNoCorsGuard)
    RemovePrivilegedNoCorsRequestHeaders();
}

void Headers::remove(ScriptState* script_state,
                     const String& name,
                     ExceptionState& exception_state) {
  // "The delete(|name|) method, when invoked, must run these steps:"
  // "1. If name is not a name, throw a TypeError."
  if (!FetchHeaderList::IsValidHeaderName(name)) {
    exception_state.ThrowTypeError("Invalid name");
    return;
  }
  // "2. If guard is |immutable|, throw a TypeError."
  if (guard_ == kImmutableGuard) {
    exception_state.ThrowTypeError("Headers are immutable");
    return;
  }
  // UseCounter for usages of "set-cookie" in kRequestGuard'ed Headers.
  if (guard_ == kRequestGuard && name.LowerASCII() == "set-cookie") {
    ExecutionContext* execution_context = ExecutionContext::From(script_state);
    UseCounter::Count(execution_context,
                      WebFeature::kFetchSetCookieInRequestGuardedHeaders);
  }
  // "3. Otherwise, if guard is |request| and |name| is a forbidden header
  //     name, return."
  if (guard_ == kRequestGuard && cors::IsForbiddenHeaderName(name))
    return;
  // "4. Otherwise, if the context object’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, return."
  if (guard_ == kRequestNoCorsGuard &&
      !cors::IsNoCorsSafelistedHeaderName(name) &&
      !cors::IsPrivilegedNoCorsHeaderName(name)) {
    return;
  }
  // "5. Otherwise, if guard is |response| and |name| is a forbidden response
  //     header name, return."
  if (guard_ == kResponseGuard &&
      FetchUtils::IsForbiddenResponseHeaderName(name)) {
    return;
  }
  // "6. If this’s header list does not contain |name|, then return."
  if (!header_list_->Has(name))
    return;
  // "7. Delete |name| from header list."
  header_list_->Remove(name);
  // "8. If this’s guard is |request-no-cors|, then remove privileged no-CORS
  // request headers from this."
  if (guard_ == kRequestNoCorsGuard)
    RemovePrivilegedNoCorsRequestHeaders();
}

String Headers::get(const String& name, ExceptionState& exception_state) {
  // "The get(|name|) method, when invoked, must run these steps:"
  // "1. If |name| is not a name, throw a TypeError."
  if (!FetchHeaderList::IsValidHeaderName(name)) {
    exception_state.ThrowTypeError("Invalid name");
    return String();
  }
  // "2. If there is no header in header list whose name is |name|,
  //     return null."
  // "3. Return the combined value given |name| and header list."
  String result;
  header_list_->Get(name, result);
  return result;
}

bool Headers::has(const String& name, ExceptionState& exception_state) {
  // "The has(|name|) method, when invoked, must run these steps:"
  // "1. If |name| is not a name, throw a TypeError."
  if (!FetchHeaderList::IsValidHeaderName(name)) {
    exception_state.ThrowTypeError("Invalid name");
    return false;
  }
  // "2. Return true if there is a header in header list whose name is |name|,
  //     and false otherwise."
  return header_list_->Has(name);
}

void Headers::set(ScriptState* script_state,
                  const String& name,
                  const String& value,
                  ExceptionState& exception_state) {
  // "The set(|name|, |value|) method, when invoked, must run these steps:"
  // "1. Normalize |value|."
  const String normalized_value = FetchUtils::NormalizeHeaderValue(value);
  // "2. If |name| is not a name or |value| is not a value, throw a
  //     TypeError."
  if (!FetchHeaderList::IsValidHeaderName(name)) {
    exception_state.ThrowTypeError("Invalid name");
    return;
  }
  if (!FetchHeaderList::IsValidHeaderValue(normalized_value)) {
    exception_state.ThrowTypeError("Invalid value");
    return;
  }
  // "3. If guard is |immutable|, throw a TypeError."
  if (guard_ == kImmutableGuard) {
    exception_state.ThrowTypeError("Headers are immutable");
    return;
  }
  // UseCounter for usages of "set-cookie" in kRequestGuard'ed Headers.
  if (guard_ == kRequestGuard && name.LowerASCII() == "set-cookie") {
    ExecutionContext* execution_context = ExecutionContext::From(script_state);
    UseCounter::Count(execution_context,
                      WebFeature::kFetchSetCookieInRequestGuardedHeaders);
  }
  // "4. Otherwise, if guard is |request| and |name| is a forbidden header
  //     name, return."
  if (guard_ == kRequestGuard && cors::IsForbiddenHeaderName(name))
    return;
  // "5. Otherwise, if guard is |request-no-CORS| and |name|/|value| is not a
  //     no-CORS-safelisted header, return."
  if (guard_ == kRequestNoCorsGuard &&
      !cors::IsNoCorsSafelistedHeader(name, normalized_value)) {
    return;
  }
  // "6. Otherwise, if guard is |response| and |name| is a forbidden response
  //     header name, return."
  if (guard_ == kResponseGuard &&
      FetchUtils::IsForbiddenResponseHeaderName(name)) {
    return;
  }
  // "7. Set |name|/|value| in header list."
  header_list_->Set(name, normalized_value);
  // "8. If this’s guard is |request-no-cors|, then remove privileged no-CORS
  // request headers from this."
  if (guard_ == kRequestNoCorsGuard)
    RemovePrivilegedNoCorsRequestHeaders();
}

// This overload is not called directly by Web APIs, but rather by other C++
// classes. For example, when initializing a Request object it is possible that
// a Request's Headers must be filled with an existing Headers object.
void Headers::FillWith(ScriptState* script_state,
                       const Headers* object,
                       ExceptionState& exception_state) {
  DCHECK_EQ(header_list_->size(), 0U);
  for (const auto& header : object->header_list_->List()) {
    append(script_state, header.first, header.second, exception_state);
    if (exception_state.HadException())
      return;
  }
}

void Headers::FillWith(ScriptState* script_state,
                       const V8HeadersInit* init,
                       ExceptionState& exception_state) {
  DCHECK_EQ(header_list_->size(), 0U);

  if (!init)
    return;

  switch (init->GetContentType()) {
    case V8HeadersInit::ContentType::kByteStringByteStringRecord:
      return FillWith(script_state, init->GetAsByteStringByteStringRecord(),
                      exception_state);
    case V8HeadersInit::ContentType::kByteStringSequenceSequence:
      return FillWith(script_state, init->GetAsByteStringSequenceSequence(),
                      exception_state);
  }

  NOTREACHED();
}

void Headers::FillWith(ScriptState* script_state,
                       const Vector<Vector<String>>& object,
                       ExceptionState& exception_state) {
  DCHECK(!header_list_->size());
  // "1. If |object| is a sequence, then for each |header| in |object|, run
  //     these substeps:
  //     1. If |header| does not contain exactly two items, then throw a
  //        TypeError.
  //     2. Append |header|’s first item/|header|’s second item to |headers|.
  //        Rethrow any exception."
  for (wtf_size_t i = 0; i < object.size(); ++i) {
    if (object[i].size() != 2) {
      exception_state.ThrowTypeError("Invalid value");
      return;
    }
    append(script_state, object[i][0], object[i][1], exception_state);
    if (exception_state.HadException())
      return;
  }
}

void Headers::FillWith(ScriptState* script_state,
                       const Vector<std::pair<String, String>>& object,
                       ExceptionState& exception_state) {
  DCHECK(!header_list_->size());

  for (const auto& item : object) {
    append(script_state, item.first, item.second, exception_state);
    if (exception_state.HadException())
      return;
  }
}

void Headers::RemovePrivilegedNoCorsRequestHeaders() {
  const Vector<String> privileged_no_cors_header_names =
      cors::PrivilegedNoCorsHeaderNames();
  for (const auto& header : privileged_no_cors_header_names)
    header_list_->Remove(header);
}

Headers::Headers()
    : header_list_(MakeGarbageCollected<FetchHeaderList>()),
      guard_(kNoneGuard) {}

Headers::Headers(FetchHeaderList* header_list)
    : header_list_(header_list), guard_(kNoneGuard) {}

void Headers::Trace(Visitor* visitor) const {
  visitor->Trace(header_list_);
  ScriptWrappable::Trace(visitor);
}

PairIterable<String, IDLString, String, IDLString>::IterationSource*
Headers::StartIteration(ScriptState*, ExceptionState&) {
  return MakeGarbageCollected<HeadersIterationSource>(header_list_);
}

}  // namespace blink