File: topic_subscription_request.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 (246 lines) | stat: -rw-r--r-- 8,691 bytes parent folder | download | duplicates (6)
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
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/carrier_lock/topic_subscription_request.h"

#include "base/json/json_writer.h"
#include "base/location.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/escape.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/values.h"
#include "google_apis/credentials_mode.h"
#include "net/base/load_flags.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_status_code.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"
#include "url/gurl.h"

namespace ash::carrier_lock {

namespace {

const char kTopicSubscriptionRequestContentType[] =
    "application/x-www-form-urlencoded";
const char kFcmRegistrationUrl[] =
    "https://android.clients.google.com/c2dm/register3";

// Request constants.
const char kAppKey[] = "app";
const char kSenderKey[] = "sender";
const char kDeviceKey[] = "device";
const char kTopicKey[] = "X-gcm.topic";
const char kDeleteKey[] = "delete";
const char kLoginHeader[] = "AidLogin";

// Response constants.
const char kErrorPrefix[] = "Error=";
const char kAuthenticationFailed[] = "AUTHENTICATION_FAILED";
const char kInvalidSender[] = "INVALID_SENDER";
const char kInvalidParameters[] = "INVALID_PARAMETERS";
const char kInternalServerError[] = "InternalServerError";
const char kQuotaExceeded[] = "QUOTA_EXCEEDED";
const char kTooManySubscribers[] = "TOO_MANY_SUBSCRIBERS";

// Gets correct status from the error message.
Result GetStatusFromError(std::string& error) {
  if (error.find(kAuthenticationFailed) != std::string::npos) {
    error = kAuthenticationFailed;
    return Result::kInvalidInput;
  }
  if (error.find(kInvalidSender) != std::string::npos) {
    error = kInvalidSender;
    return Result::kInvalidInput;
  }
  if (error.find(kInvalidParameters) != std::string::npos) {
    error = kInvalidParameters;
    return Result::kInvalidInput;
  }
  if (error.find(kInternalServerError) != std::string::npos) {
    error = kInternalServerError;
    return Result::kServerInternalError;
  }
  if (error.find(kQuotaExceeded) != std::string::npos) {
    error = kQuotaExceeded;
    return Result::kServerInternalError;
  }
  if (error.find(kTooManySubscribers) != std::string::npos) {
    error = kTooManySubscribers;
    return Result::kServerInternalError;
  }

  // Handle unknown errors.
  size_t pos = std::size(kErrorPrefix);
  error = error.substr(pos, error.size() - pos);
  return Result::kRequestFailed;
}

// Create encoding: "key=value" and append it to "out" string
void BuildFormEncoding(const std::string& key,
                       const std::string& value,
                       std::string* out) {
  if (!out->empty()) {
    out->append("&");
  }
  out->append(key + "=" + base::EscapeUrlEncodedData(value, true));
}

}  // namespace

TopicSubscriptionRequest::RequestInfo::RequestInfo(uint64_t android_id,
                                                   uint64_t security_token,
                                                   const std::string& app_id,
                                                   const std::string& token,
                                                   const std::string& topic,
                                                   bool unsubscribe)
    : android_id(android_id),
      security_token(security_token),
      app_id(app_id),
      token(token),
      topic(topic),
      unsubscribe(unsubscribe) {
  DCHECK(android_id != 0UL);
  DCHECK(security_token != 0UL);
  DCHECK(!app_id.empty());
  DCHECK(!token.empty());
  DCHECK(!topic.empty());
}

TopicSubscriptionRequest::RequestInfo::RequestInfo(const RequestInfo&) =
    default;

TopicSubscriptionRequest::RequestInfo::~RequestInfo() = default;

TopicSubscriptionRequest::TopicSubscriptionRequest(
    const RequestInfo& request_info,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    Callback callback)
    : request_callback_(std::move(callback)),
      request_info_(request_info),
      url_loader_factory_(std::move(url_loader_factory)) {
  topic_subscription_url_ = GURL(kFcmRegistrationUrl);
}

TopicSubscriptionRequest::~TopicSubscriptionRequest() = default;

void TopicSubscriptionRequest::Start() {
  DCHECK(!request_callback_.is_null());
  DCHECK(!url_loader_.get());

  net::NetworkTrafficAnnotationTag traffic_annotation =
      net::DefineNetworkTrafficAnnotation("carrier_lock_manager_fcm_topic", R"(
        semantics {
          sender: "Carrier Lock manager"
          description:
            "Carrier Lock Manager subscribes to public topics on FCM"
            "to receive push notifications in case of lock changes."
          trigger: "This request happens once on every boot if the device"
                   "has carrier lock enabled."
          data:
            "The topic name and a registration token."
          destination: GOOGLE_OWNED_SERVICE
          internal {
            contacts {
                email: "cros-cellular-core@google.com"
            }
          }
          user_data {
            type: ACCESS_TOKEN
          }
          last_reviewed: "2023-10-24"
        }
        policy {
          cookies_allowed: NO
          setting: "This feature cannot be disabled in settings."
          policy_exception_justification: "Carrier Lock is always enforced."
        })");
  auto request = std::make_unique<network::ResourceRequest>();
  request->url = topic_subscription_url_;
  request->method = "POST";
  request->credentials_mode =
      google_apis::GetOmitCredentialsModeForGaiaRequests();

  request->headers.SetHeader(
      net::HttpRequestHeaders::kAuthorization,
      std::string(kLoginHeader) + " " +
          base::NumberToString(request_info_.android_id) + ":" +
          base::NumberToString(request_info_.security_token));

  std::string body;
  BuildFormEncoding(kDeviceKey, base::NumberToString(request_info_.android_id),
                    &body);
  BuildFormEncoding(kAppKey, request_info_.app_id, &body);
  BuildFormEncoding(kSenderKey, request_info_.token, &body);
  BuildFormEncoding(kTopicKey, request_info_.topic, &body);
  if (request_info_.unsubscribe) {
    BuildFormEncoding(kDeleteKey, "true", &body);
  }

  url_loader_ =
      network::SimpleURLLoader::Create(std::move(request), traffic_annotation);
  url_loader_->AttachStringForUpload(body,
                                     kTopicSubscriptionRequestContentType);
  url_loader_->SetAllowHttpErrorResults(true);
  url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      url_loader_factory_.get(),
      base::BindOnce(&TopicSubscriptionRequest::OnUrlLoadComplete,
                     base::Unretained(this), url_loader_.get()));
}

void TopicSubscriptionRequest::OnUrlLoadComplete(
    const network::SimpleURLLoader* source,
    std::unique_ptr<std::string> body) {
  if (source->NetError() != net::OK) {
    LOG(ERROR) << "Failed to fetch URL.";
    ReturnResult(Result::kConnectionError);
    return;
  }

  std::string response;
  if (!body) {
    LOG(ERROR) << "Failed to get response.";
    ReturnResult(Result::kConnectionError);
    return;
  }
  response = std::move(*body);

  // If we are able to parse a meaningful known error, let's do so. Note that
  // some errors will have HTTP_OK response code!
  size_t error_pos = response.find(kErrorPrefix);
  if (error_pos != std::string::npos) {
    std::string error = response.substr(error_pos);
    ReturnResult(GetStatusFromError(error));
    LOG(ERROR) << "Received error in response: " << error;
    return;
  }

  // Can't even get any header info.
  if (!source->ResponseInfo() || !source->ResponseInfo()->headers) {
    LOG(ERROR) << "Missing header in response.";
    ReturnResult(Result::kInvalidResponse);
    return;
  }

  // If we cannot tell what the error is, but at least we know response code was
  // not OK.
  if (source->ResponseInfo()->headers->response_code() != net::HTTP_OK) {
    LOG(ERROR) << "HTTP response code not OK: "
               << source->ResponseInfo()->headers->response_code();
    ReturnResult(Result::kInvalidResponse);
    return;
  }

  ReturnResult(Result::kSuccess);
}

void TopicSubscriptionRequest::ReturnResult(Result result) {
  std::move(request_callback_).Run(result);
}

}  // namespace ash::carrier_lock