summaryrefslogtreecommitdiffstats
path: root/chromium/components/policy/core/common/cloud/reporting_job_configuration_base.cc
blob: 022064e975071063866358b4dda99ecdd34d948b (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
// Copyright 2020 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 "components/policy/core/common/cloud/reporting_job_configuration_base.h"

#include <memory>
#include <string>

#include "base/callback.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "components/policy/core/common/cloud/cloud_policy_client.h"
#include "components/policy/core/common/cloud/cloud_policy_util.h"
#include "components/policy/core/common/cloud/device_management_service.h"
#include "components/policy/core/common/cloud/dm_auth.h"
#include "components/policy/policy_export.h"
#include "components/version_info/version_info.h"
#include "google_apis/google_api_keys.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "url/gurl.h"

namespace policy {

// Strings for |DeviceDictionaryBuilder|.
const char
    ReportingJobConfigurationBase::DeviceDictionaryBuilder::kDeviceKey[] =
        "device";
const char ReportingJobConfigurationBase::DeviceDictionaryBuilder::kDMToken[] =
    "dmToken";
const char ReportingJobConfigurationBase::DeviceDictionaryBuilder::kClientId[] =
    "clientId";
const char
    ReportingJobConfigurationBase::DeviceDictionaryBuilder::kOSVersion[] =
        "osVersion";
const char
    ReportingJobConfigurationBase::DeviceDictionaryBuilder::kOSPlatform[] =
        "osPlatform";
const char ReportingJobConfigurationBase::DeviceDictionaryBuilder::kName[] =
    "name";

// static
base::Value::Dict
ReportingJobConfigurationBase::DeviceDictionaryBuilder::BuildDeviceDictionary(
    const std::string& dm_token,
    const std::string& client_id) {
  base::Value::Dict device_dictionary;
  device_dictionary.Set(kDMToken, dm_token);
  device_dictionary.Set(kClientId, client_id);
  device_dictionary.Set(kOSVersion, GetOSVersion());
  device_dictionary.Set(kOSPlatform, GetOSPlatform());
  device_dictionary.Set(kName, GetDeviceName());
  return device_dictionary;
}

// static
std::string
ReportingJobConfigurationBase::DeviceDictionaryBuilder::GetDMTokenPath() {
  return GetStringPath(kDMToken);
}

// static
std::string
ReportingJobConfigurationBase::DeviceDictionaryBuilder::GetClientIdPath() {
  return GetStringPath(kClientId);
}

// static
std::string
ReportingJobConfigurationBase::DeviceDictionaryBuilder::GetOSVersionPath() {
  return GetStringPath(kOSVersion);
}

// static
std::string
ReportingJobConfigurationBase::DeviceDictionaryBuilder::GetOSPlatformPath() {
  return GetStringPath(kOSPlatform);
}

// static
std::string
ReportingJobConfigurationBase::DeviceDictionaryBuilder::GetNamePath() {
  return GetStringPath(kName);
}

// static
std::string
ReportingJobConfigurationBase::DeviceDictionaryBuilder::GetStringPath(
    base::StringPiece leaf_name) {
  return base::JoinString({kDeviceKey, leaf_name}, ".");
}

// Strings for |BrowserDictionaryBuilder|.
const char
    ReportingJobConfigurationBase::BrowserDictionaryBuilder::kBrowserKey[] =
        "browser";
const char
    ReportingJobConfigurationBase::BrowserDictionaryBuilder::kBrowserId[] =
        "browserId";
const char
    ReportingJobConfigurationBase::BrowserDictionaryBuilder::kUserAgent[] =
        "userAgent";
const char
    ReportingJobConfigurationBase::BrowserDictionaryBuilder::kMachineUser[] =
        "machineUser";
const char
    ReportingJobConfigurationBase::BrowserDictionaryBuilder::kChromeVersion[] =
        "chromeVersion";

// static
base::Value
ReportingJobConfigurationBase::BrowserDictionaryBuilder::BuildBrowserDictionary(
    bool include_device_info) {
  base::Value browser_dictionary{base::Value::Type::DICTIONARY};

  base::FilePath browser_id;
  if (base::PathService::Get(base::DIR_EXE, &browser_id)) {
    browser_dictionary.SetStringKey(kBrowserId, browser_id.AsUTF8Unsafe());
  }

  if (include_device_info)
    browser_dictionary.SetStringKey(kMachineUser, GetOSUsername());

  browser_dictionary.SetStringKey(kChromeVersion,
                                  version_info::GetVersionNumber());
  return browser_dictionary;
}

// static
std::string
ReportingJobConfigurationBase::BrowserDictionaryBuilder::GetBrowserIdPath() {
  return GetStringPath(kBrowserId);
}

// static
std::string
ReportingJobConfigurationBase::BrowserDictionaryBuilder::GetUserAgentPath() {
  return GetStringPath(kUserAgent);
}

// static
std::string
ReportingJobConfigurationBase::BrowserDictionaryBuilder::GetMachineUserPath() {
  return GetStringPath(kMachineUser);
}

// static
std::string ReportingJobConfigurationBase::BrowserDictionaryBuilder::
    GetChromeVersionPath() {
  return GetStringPath(kChromeVersion);
}

// static
std::string
ReportingJobConfigurationBase::BrowserDictionaryBuilder::GetStringPath(
    base::StringPiece leaf_name) {
  return base::JoinString({kBrowserKey, leaf_name}, ".");
}

std::string ReportingJobConfigurationBase::GetPayload() {
  // Move context keys to the payload.
  if (context_.has_value()) {
    payload_.Merge(*context_);
    context_.reset();
  }

  // Allow children to mutate the payload if need be.
  UpdatePayloadBeforeGetInternal();

  std::string payload_string;
  base::JSONWriter::Write(payload_, &payload_string);
  return payload_string;
}

std::string ReportingJobConfigurationBase::GetUmaName() {
  return GetUmaString() + GetJobTypeAsString(GetType());
}

DeviceManagementService::Job::RetryMethod
ReportingJobConfigurationBase::ShouldRetry(int response_code,
                                           const std::string& response_body) {
  // If the request wasn't successfully processed at all, resending it won't do
  // anything. Don't retry.
  if (response_code != DeviceManagementService::kSuccess) {
    return DeviceManagementService::Job::NO_RETRY;
  }

  // Allow child to determine if any portion of the message should be retried.
  return ShouldRetryInternal(response_code, response_body);
}

void ReportingJobConfigurationBase::OnBeforeRetry(
    int response_code,
    const std::string& response_body) {
  // If the request wasn't successful, don't try to retry.
  if (response_code != DeviceManagementService::kSuccess) {
    return;
  }

  OnBeforeRetryInternal(response_code, response_body);
}

void ReportingJobConfigurationBase::OnURLLoadComplete(
    DeviceManagementService::Job* job,
    int net_error,
    int response_code,
    const std::string& response_body) {
  absl::optional<base::Value> response = base::JSONReader::Read(response_body);

  // Parse the response even if |response_code| is not a success since the
  // response data may contain an error message.
  // Map the net_error/response_code to a DeviceManagementStatus.
  DeviceManagementStatus code;
  if (net_error != net::OK) {
    code = DM_STATUS_REQUEST_FAILED;
  } else {
    switch (response_code) {
      case DeviceManagementService::kSuccess:
        code = DM_STATUS_SUCCESS;
        break;
      case DeviceManagementService::kInvalidArgument:
        code = DM_STATUS_REQUEST_INVALID;
        break;
      case DeviceManagementService::kInvalidAuthCookieOrDMToken:
        code = DM_STATUS_SERVICE_MANAGEMENT_TOKEN_INVALID;
        break;
      case DeviceManagementService::kDeviceManagementNotAllowed:
        code = DM_STATUS_SERVICE_MANAGEMENT_NOT_SUPPORTED;
        break;
      default:
        // Handle all unknown 5xx HTTP error codes as temporary and any other
        // unknown error as one that needs more time to recover.
        if (response_code >= 500 && response_code <= 599)
          code = DM_STATUS_TEMPORARY_UNAVAILABLE;
        else
          code = DM_STATUS_HTTP_STATUS_ERROR;
        break;
    }
  }

  auto response_dict = response && response->is_dict()
                           ? absl::make_optional(std::move(response->GetDict()))
                           : absl::nullopt;
  std::move(callback_).Run(job, code, net_error, std::move(response_dict));
}

DeviceManagementService::Job::RetryMethod
ReportingJobConfigurationBase::ShouldRetryInternal(
    int response_code,
    const std::string& response_body) {
  return JobConfigurationBase::ShouldRetry(response_code, response_body);
}

void ReportingJobConfigurationBase::OnBeforeRetryInternal(
    int response_code,
    const std::string& response_body) {}

void ReportingJobConfigurationBase::UpdatePayloadBeforeGetInternal() {}

GURL ReportingJobConfigurationBase::GetURL(int last_error) const {
  return GURL(server_url_);
}

ReportingJobConfigurationBase::ReportingJobConfigurationBase(
    JobType type,
    scoped_refptr<network::SharedURLLoaderFactory> factory,
    CloudPolicyClient* client,
    const std::string& server_url,
    bool include_device_info,
    UploadCompleteCallback callback)
    : JobConfigurationBase(type,
                           DMAuth::FromDMToken(client->dm_token()),
                           /*oauth_token=*/absl::nullopt,
                           factory),
      callback_(std::move(callback)),
      server_url_(server_url) {
  DCHECK(GetAuth().has_dm_token());
  InitializePayload(client, include_device_info);
}

ReportingJobConfigurationBase::~ReportingJobConfigurationBase() = default;

void ReportingJobConfigurationBase::InitializePayload(
    CloudPolicyClient* client,
    bool include_device_info) {
  AddParameter("key", google_apis::GetAPIKey());

  if (include_device_info) {
    payload_.Set(DeviceDictionaryBuilder::kDeviceKey,
                 DeviceDictionaryBuilder::BuildDeviceDictionary(
                     client->dm_token(), client->client_id()));
  }
  payload_.Set(
      BrowserDictionaryBuilder::kBrowserKey,
      BrowserDictionaryBuilder::BuildBrowserDictionary(include_device_info));
}

}  // namespace policy