File: api_guard_delegate.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 (275 lines) | stat: -rw-r--r-- 10,350 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
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
// 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/chromeos/extensions/telemetry/api/common/api_guard_delegate.h"

#include <optional>
#include <string>
#include <utility>

#include "ash/constants/ash_features.h"
#include "base/command_line.h"
#include "base/containers/flat_set.h"
#include "base/containers/queue.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/weak_ptr.h"
#include "base/values.h"
#include "chrome/browser/chromeos/extensions/telemetry/api/common/hardware_info_delegate.h"
#include "chrome/browser/chromeos/extensions/telemetry/api/common/util.h"
#include "chrome/browser/extensions/extension_management.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chromeos/extensions/chromeos_system_extension_info.h"
#include "chromeos/ash/components/browser_context_helper/browser_context_types.h"
#include "components/account_id/account_id.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "extensions/common/extension.h"

namespace content {
class BrowserContext;
}

namespace chromeos {

namespace switches {

// Skips the check for the device manufacturer.
// Used for development/testing.
const char kTelemetryExtensionSkipManufacturerCheckForTesting[] =
    "telemetry-extension-skip-manufacturer-check-for-testing";

}  // namespace switches

namespace {

using CheckCallback = base::OnceCallback<void(bool)>;

// A helper class to check some conditions asynchronously. All the checks will
// be performed sequentially. If any checker returns false, the rest won't be
// executed and `result_callback` will be called with a corresponding
// `error_message`. After checking all the conditions, `result_callback` is
// called with nullopt.
class AsyncConditionChecker {
 public:
  explicit AsyncConditionChecker(
      base::OnceCallback<void(std::optional<std::string>)> result_callback);
  AsyncConditionChecker(AsyncConditionChecker&) = delete;
  AsyncConditionChecker& operator=(AsyncConditionChecker&) = delete;
  ~AsyncConditionChecker();

  // Appends a checker and an error message to return when check fails. A
  // checker is a `OnceCallback`. It should takes a callback and reply a boolean
  // as result to it.
  void AppendChecker(base::OnceCallback<void(CheckCallback)> checker,
                     const std::string& error_message);
  // Same as above, but also accepts a sync checker for convenience. A sync
  // checker is a `OnceCallback` which returns a boolean as result (instead of
  // passing the result to a callback).
  void AppendChecker(base::OnceCallback<bool(void)> checker,
                     const std::string& error_message);

  // Starts the check.
  void Run();

 private:
  void OnCheckFinished(const std::string& error_message, bool result);

  base::OnceCallback<void(std::optional<std::string>)> result_callback_;
  base::queue<std::pair<base::OnceCallback<void(CheckCallback)>, std::string>>
      callback_queue_;

  base::WeakPtrFactory<AsyncConditionChecker> weak_factory_{this};
};

AsyncConditionChecker::AsyncConditionChecker(
    base::OnceCallback<void(std::optional<std::string>)> result_callback)
    : result_callback_(std::move(result_callback)) {}

AsyncConditionChecker::~AsyncConditionChecker() = default;

void AsyncConditionChecker::AppendChecker(
    base::OnceCallback<void(CheckCallback)> checker,
    const std::string& error_message) {
  callback_queue_.push(std::make_pair(std::move(checker), error_message));
}

void AsyncConditionChecker::AppendChecker(
    base::OnceCallback<bool(void)> checker,
    const std::string& error_message) {
  callback_queue_.push(std::make_pair(
      base::BindOnce(
          [](base::OnceCallback<bool(void)> checker, CheckCallback check) {
            std::move(checker).Then(std::move(check)).Run();
          },
          std::move(checker)),
      error_message));
}

void AsyncConditionChecker::Run() {
  if (callback_queue_.empty()) {
    std::move(result_callback_).Run(std::nullopt);
    return;
  }

  auto [checker, error_message] = std::move(callback_queue_.front());
  callback_queue_.pop();
  std::move(checker).Run(base::BindOnce(&AsyncConditionChecker::OnCheckFinished,
                                        weak_factory_.GetWeakPtr(),
                                        error_message));
}

void AsyncConditionChecker::OnCheckFinished(const std::string& error_message,
                                            bool result) {
  if (!result) {
    std::move(result_callback_).Run(error_message);
    return;
  }
  Run();
}

bool IsExtensionForceInstalled(content::BrowserContext* context,
                               const std::string& extension_id) {
  const auto force_install_list =
      extensions::ExtensionManagementFactory::GetForBrowserContext(context)
          ->GetForceInstallList();
  return force_install_list.Find(extension_id) != nullptr;
}

void OnGetManufacturer(const std::string& extension_id,
                       CheckCallback callback,
                       const std::string& actual_manufacturer) {
  const auto& extension_info = GetChromeOSExtensionInfoById(extension_id);
  const auto& expected_manufacturers = extension_info.manufacturers;
  std::move(callback).Run(expected_manufacturers.contains(actual_manufacturer));
}

void IsExpectedManufacturerForExtensionId(const std::string& extension_id,
                                          CheckCallback callback) {
  auto& hardware_info_delegate = HardwareInfoDelegate::Get();
  hardware_info_delegate.GetManufacturer(
      base::BindOnce(&OnGetManufacturer, extension_id, std::move(callback)));
}

bool IsExtensionUsedByShimlessRMA(content::BrowserContext* context) {
  return ::ash::features::IsShimlessRMA3pDiagnosticsEnabled() &&
         ::ash::IsShimlessRmaAppBrowserContext(context);
}

bool IsCurrentUserAffiliated() {
  auto* active_user = user_manager::UserManager::Get()->GetActiveUser();
  CHECK(active_user);
  return active_user->IsAffiliated();
}

void IsCurrentUserOwnerOnOwnerFetched(CheckCallback callback) {
  std::move(callback).Run(
      user_manager::UserManager::Get()->IsCurrentUserOwner());
}

void IsCurrentUserOwner(content::BrowserContext* context,
                        CheckCallback callback) {
  auto on_owner_fetched = base::IgnoreArgs<const AccountId&>(
      base::BindOnce(&IsCurrentUserOwnerOnOwnerFetched, std::move(callback)));

  user_manager::UserManager::Get()->GetOwnerAccountIdAsync(
      std::move(on_owner_fetched));
}

class ApiGuardDelegateImpl : public ApiGuardDelegate {
 public:
  ApiGuardDelegateImpl();
  ApiGuardDelegateImpl(const ApiGuardDelegateImpl&) = delete;
  ApiGuardDelegateImpl& operator=(const ApiGuardDelegateImpl&) = delete;
  ~ApiGuardDelegateImpl() override;

  // ApiGuardDelegate:
  // As agreed with the privacy team, telemetry APIs can be accessed if all the
  // following constraints are satisfied:
  // 1. The user is either:
  //    a. managed and the extension was force-installed via policy, or
  //    b. the user is the device owner, or
  //    c. the user is in the Shimless RMA flow.
  // 2. The PWA UI associated with the extension must be opened.
  // 3. The device hardware belongs to the OEM associated with the extension.
  void CanAccessApi(content::BrowserContext* context,
                    const extensions::Extension* extension,
                    CanAccessApiCallback callback) override;

 private:
  std::unique_ptr<AsyncConditionChecker> condition_checker_;
};

ApiGuardDelegateImpl::ApiGuardDelegateImpl() = default;

ApiGuardDelegateImpl::~ApiGuardDelegateImpl() = default;

void ApiGuardDelegateImpl::CanAccessApi(content::BrowserContext* context,
                                        const extensions::Extension* extension,
                                        CanAccessApiCallback callback) {
  condition_checker_ =
      std::make_unique<AsyncConditionChecker>(std::move(callback));

  // base::Unretained is safe to use for a pointer to Extension and Context,
  // because both the extension and the context outlive the delegate by
  // definition (since this is executed as part of an extension API call), and
  // these callbacks are bound to the `condition_checker_`, which is bound to
  // the delegate.

  if (IsExtensionUsedByShimlessRMA(context)) {
    // No user to check for the Shimless RMA flow. Note that in this
    // case there is no active user in UserManager.
  } else if (IsCurrentUserAffiliated()) {
    condition_checker_->AppendChecker(
        base::BindOnce(&IsExtensionForceInstalled, base::Unretained(context),
                       extension->id()),
        "This extension is not installed by the admin");
  } else {
    condition_checker_->AppendChecker(
        base::BindOnce(&IsCurrentUserOwner, base::Unretained(context)),
        "This extension is not run by the device owner");
  }

  condition_checker_->AppendChecker(
      base::BindOnce(&IsTelemetryExtensionAppUiOpenAndSecure,
                     base::Unretained(context), base::Unretained(extension)),
      "Companion app UI is not open or not secure");

  if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kTelemetryExtensionSkipManufacturerCheckForTesting)) {
    condition_checker_->AppendChecker(
        base::BindOnce(&IsExpectedManufacturerForExtensionId, extension->id()),
        "This extension is not allowed to access the API on this device");
  }

  condition_checker_->Run();
}

}  // namespace

// static
ApiGuardDelegate::Factory* ApiGuardDelegate::Factory::test_factory_ = nullptr;

// static
std::unique_ptr<ApiGuardDelegate> ApiGuardDelegate::Factory::Create() {
  if (test_factory_) {
    return test_factory_->CreateInstance();
  }
  return base::WrapUnique<ApiGuardDelegate>(new ApiGuardDelegateImpl());
}

// static
void ApiGuardDelegate::Factory::SetForTesting(Factory* test_factory) {
  test_factory_ = test_factory;
}

ApiGuardDelegate::Factory::Factory() = default;
ApiGuardDelegate::Factory::~Factory() = default;

ApiGuardDelegate::ApiGuardDelegate() = default;
ApiGuardDelegate::~ApiGuardDelegate() = default;

}  // namespace chromeos