File: http_exchange.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (420 lines) | stat: -rw-r--r-- 13,512 bytes parent folder | download | duplicates (5)
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/printing/oauth2/http_exchange.h"

#include <string>
#include <utility>

#include "base/functional/bind.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/notreached.h"
#include "base/strings/escape.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/url_response_head.mojom.h"

namespace ash {
namespace printing {
namespace oauth2 {

namespace {

// Converts ContentFormat to MIME string.
std::string ToString(ContentFormat format) {
  switch (format) {
    case ContentFormat::kJson:
      return "application/json";
    case ContentFormat::kXWwwFormUrlencoded:
      return "application/x-www-form-urlencoded";
    default:
      NOTREACHED();
  }
}

}  // namespace

HttpExchange::HttpExchange(
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
    : url_loader_factory_(url_loader_factory) {}

HttpExchange::~HttpExchange() = default;

void HttpExchange::Clear() {
  content_.clear();
  error_msg_.clear();
  url_loader_.reset();
}

void HttpExchange::AddParamString(const std::string& name,
                                  const std::string& value) {
  DCHECK(!name.empty());
  content_.Set(name, value);
}

void HttpExchange::AddParamArrayString(const std::string& name,
                                       const std::vector<std::string>& value) {
  DCHECK(!name.empty());
  base::Value::List list_node;
  for (const auto& value_element : value) {
    list_node.Append(value_element);
  }
  content_.Set(name, std::move(list_node));
}

void HttpExchange::Exchange(
    const std::string& http_method,
    const GURL& url,
    ContentFormat request_format,
    int success_http_status,
    int error_http_status,
    const net::PartialNetworkTrafficAnnotationTag& partial_traffic_annotation,
    OnExchangeCompletedCallback callback) {
  std::string data;
  // Converts `content_` to `data`.
  if (request_format == ContentFormat::kJson) {
    if (!base::JSONWriter::Write(content_, &data)) {
      error_msg_ = "Cannot create JSON payload.";
      std::move(callback).Run(StatusCode::kUnexpectedError);
      return;
    }
  } else if (request_format == ContentFormat::kXWwwFormUrlencoded) {
    for (const auto kv : content_) {
      if (!data.empty()) {
        data += "&";
      }
      data += base::EscapeUrlEncodedData(kv.first, true);
      data += "=";
      switch (kv.second.type()) {
        case base::Value::Type::BOOLEAN:
          data += (kv.second.GetBool()) ? ("true") : ("false");
          break;
        case base::Value::Type::INTEGER:
          data += base::NumberToString(kv.second.GetInt());
          break;
        case base::Value::Type::STRING:
          data += base::EscapeUrlEncodedData(kv.second.GetString(), true);
          break;
        default:
          error_msg_ = "Cannot save a vector value as x-www-form-urlencoded.";
          std::move(callback).Run(StatusCode::kUnexpectedError);
          return;
      }
    }
  }

  // Prepares `url_loader_`.
  auto resource_request = std::make_unique<network::ResourceRequest>();
  resource_request->method = http_method;
  resource_request->url = url;
  resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit;
  resource_request->headers.SetHeader("Accept", "application/json");
  net::NetworkTrafficAnnotationTag traffic_annotation =
      net::CompleteNetworkTrafficAnnotation("printing_oauth2_http_exchange",
                                            partial_traffic_annotation, R"(
        semantics {
          sender: "Printers Manager"
          trigger: "User tries to use a printer that requires OAuth2 "
            "authorization."
          destination: OTHER
          destination_other: "Trusted Authorization Server"
        }
        policy {
          cookies_allowed: NO
          setting:
            "You can enable or disable this experimental feature via 'Enable "
            "OAuth when printing via the IPP protocol' on the chrome://flags "
            "tab."
          policy_exception_justification: "This is an experimental feature. "
            "The policy controlling this feature does not yet exist."
        })");
  url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request),
                                                 traffic_annotation);

  // Sets the payload.
  if (request_format != ContentFormat::kEmpty) {
    url_loader_->AttachStringForUpload(data, ToString(request_format));
  }
  // We want to receive the body even on error, as it may contain the reason
  // for failure.
  url_loader_->SetAllowHttpErrorResults(true);
  // It's safe to use Unretained below as the |url_loader_| is owned by
  // |this|.
  url_loader_->DownloadToString(
      url_loader_factory_.get(),
      base::BindOnce(&HttpExchange::OnURLLoaderCompleted,
                     base::Unretained(this), success_http_status,
                     error_http_status, std::move(callback)),
      1024 * 1024);
}

void HttpExchange::OnURLLoaderCompleted(
    int success_http_status,
    int error_http_status,
    OnExchangeCompletedCallback callback,
    std::unique_ptr<std::string> response_body) {
  // Checks for connection errors.
  const int net_error = url_loader_->NetError();
  if (!(net_error == net::OK && url_loader_->ResponseInfo() &&
        url_loader_->ResponseInfo()->headers)) {
    error_msg_ = base::StringPrintf("NetError=%d", net_error);
    std::move(callback).Run(StatusCode::kConnectionError);
    return;
  }

  // Checks for special HTTP status codes.
  const auto http_status = GetHttpStatus();
  if (http_status == 500) {
    error_msg_ = "Internal Server Error (HTTP status code=500)";
    std::move(callback).Run(StatusCode::kServerError);
    return;
  }
  if (http_status == 503) {
    error_msg_ = "Service Unavailable (HTTP status code=503)";
    std::move(callback).Run(StatusCode::kServerTemporarilyUnavailable);
    return;
  }
  if (http_status != success_http_status && http_status != error_http_status) {
    error_msg_ = "Unexpected HTTP status: " + base::NumberToString(http_status);
    std::move(callback).Run(StatusCode::kInvalidResponse);
    return;
  }

  // Checks if response body (payload) exists.
  if (!response_body || response_body->empty()) {
    error_msg_ = "Missing payload.";
    std::move(callback).Run(StatusCode::kInvalidResponse);
    return;
  }

  // Checks if the payload contains a JSON dictionary.
  std::string mime_type;
  std::string charset;
  url_loader_->ResponseInfo()->headers->GetMimeTypeAndCharset(&mime_type,
                                                              &charset);
  if (mime_type != "application/json") {
    error_msg_ = "Unexpected type of payload: " + mime_type;
    std::move(callback).Run(StatusCode::kInvalidResponse);
    return;
  }
  if (!charset.empty() && charset != "utf-8" && charset != "ascii") {
    error_msg_ = "Unsupported charset: " + charset;
    std::move(callback).Run(StatusCode::kInvalidResponse);
    return;
  }
  auto parsed = base::JSONReader::ReadDict(*response_body);
  if (!parsed) {
    error_msg_ = "Cannot parse JSON payload.";
    std::move(callback).Run(StatusCode::kInvalidResponse);
    return;
  }
  content_ = std::move(parsed).value();

  // Exits if success.
  if (http_status == success_http_status) {
    std::move(callback).Run(StatusCode::kOK);
    return;
  }

  // Parses error response.
  std::string error;
  std::string error_description;
  std::string error_uri;
  if (!ParamStringGet("error", true, &error) ||
      !ParamStringGet("error_description", false, &error_description) ||
      !ParamStringGet("error_uri", false, &error_uri)) {
    std::move(callback).Run(StatusCode::kInvalidResponse);
    return;
  }

  // Handles the error response.
  error_msg_ = "error=" + error;
  if (!error_description.empty()) {
    error_msg_ += base::StrCat({"; description=", error_description});
  }
  if (!error_uri.empty()) {
    error_msg_ += base::StrCat({"; uri=", error_uri});
  }
  if (error == "invalid_grant") {
    std::move(callback).Run(StatusCode::kInvalidAccessToken);
  } else {
    std::move(callback).Run(StatusCode::kAccessDenied);
  }
}

int HttpExchange::GetHttpStatus() const {
  if (url_loader_ && url_loader_->ResponseInfo() &&
      url_loader_->ResponseInfo()->headers) {
    return url_loader_->ResponseInfo()->headers->response_code();
  }
  return 0;
}

bool HttpExchange::ParamArrayStringContains(const std::string& name,
                                            bool required,
                                            const std::string& value) {
  base::Value* node = FindNode(name, required);
  if (!node) {
    return !required;
  }
  if (!node->is_list()) {
    error_msg_ = base::StrCat({"Field ", name, " must be an array."});
    return false;
  }
  const auto& node_as_list = node->GetList();
  for (auto& element : node_as_list) {
    if (element.is_string() && element.GetString() == value) {
      // Success!
      return true;
    }
  }
  error_msg_ =
      base::StrCat({"Field ", name, " must contain the value '", value, "'"});
  return false;
}

bool HttpExchange::ParamArrayStringEquals(
    const std::string& name,
    bool required,
    const std::vector<std::string>& value) {
  base::Value* node = FindNode(name, required);
  if (!node) {
    return !required;
  }
  if (!node->is_list()) {
    error_msg_ = base::StrCat({"Field ", name, " must be an array"});
    return false;
  }
  const base::Value::List& node_as_list = node->GetList();
  if (node_as_list.size() == value.size()) {
    // Compares the vectors, element by element.
    bool are_equal = true;
    for (size_t i = 0; i < value.size() && are_equal; ++i) {
      const auto& element = node_as_list[i];
      if (!element.is_string() || element.GetString() != value[i]) {
        are_equal = false;
      }
    }
    if (are_equal) {
      // Success!
      return true;
    }
  }
  // Vectors are different, builds an error message.
  error_msg_ = base::StrCat({"Field ", name, " must contain the value ["});
  for (auto& element : value) {
    error_msg_ += base::StrCat({"'", element, "',"});
  }
  // Removes the last comma and add a closing bracket.
  if (!value.empty()) {
    error_msg_.pop_back();
  }
  error_msg_ += "]";
  return false;
}

bool HttpExchange::ParamStringGet(const std::string& name,
                                  bool required,
                                  std::string* value) {
  base::Value* node = FindNode(name, required);
  if (!node) {
    return !required;
  }
  if (!node->is_string()) {
    error_msg_ = base::StrCat({"Field ", name, " must be a string"});
    return false;
  }
  if (required && node->GetString().empty()) {
    error_msg_ = base::StrCat({"Field ", name, " cannot be empty"});
    return false;
  }
  if (value) {
    *value = node->GetString();
  }
  return true;
}

bool HttpExchange::ParamStringEquals(const std::string& name,
                                     bool required,
                                     const std::string& value) {
  base::Value* node = FindNode(name, required);
  if (!node) {
    return !required;
  }
  if (!node->is_string()) {
    error_msg_ = base::StrCat({"Field ", name, " must be a string"});
    return false;
  }
  if (value != node->GetString()) {
    error_msg_ = base::StrCat({"Field ", name, " must be equal '", value, "'"});
    return false;
  }
  return true;
}

bool HttpExchange::ParamURLGet(const std::string& name,
                               bool required,
                               GURL* value) {
  base::Value* node = FindNode(name, required);
  if (!node) {
    return !required;
  }
  if (!node->is_string()) {
    error_msg_ = base::StrCat({"Field ", name, " must be an URL"});
    return false;
  }
  GURL gurl(node->GetString());
  if (gurl.is_valid() && gurl.IsStandard() && gurl.scheme() == "https") {
    // Success!
    if (value) {
      *value = gurl;
    }
    return true;
  }
  error_msg_ =
      base::StrCat({"Field ", name, " must be a valid URL of type 'https://'"});
  return false;
}

bool HttpExchange::ParamURLEquals(const std::string& name,
                                  bool required,
                                  const GURL& value) {
  base::Value* node = FindNode(name, required);
  if (!node) {
    return !required;
  }
  if (!node->is_string()) {
    error_msg_ = base::StrCat({"Field ", name, " must be an URL"});
    return false;
  }
  if (value != GURL(node->GetString())) {
    error_msg_ =
        base::StrCat({"Field ", name, " must be equal '", value.spec(), "'"});
    return false;
  }
  return true;
}

const std::string& HttpExchange::GetErrorMessage() const {
  return error_msg_;
}

base::Value* HttpExchange::FindNode(const std::string& name, bool required) {
  base::Value* value = content_.Find(name);
  if (required && !value) {
    error_msg_ = base::StrCat({"Field ", name, " is missing"});
  }
  return value;
}

}  // namespace oauth2
}  // namespace printing
}  // namespace ash