File: status_uploader_unittest.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 (382 lines) | stat: -rw-r--r-- 15,669 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
// Copyright 2015 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/policy/uploading/status_uploader.h"

#include <memory>
#include <tuple>
#include <utility>

#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/test/gmock_move_support.h"
#include "base/test/task_environment.h"
#include "base/test/test_simple_task_runner.h"
#include "base/time/time.h"
#include "chrome/browser/ash/policy/core/device_local_account.h"
#include "chrome/browser/ash/policy/status_collector/device_status_collector.h"
#include "chrome/browser/ash/settings/scoped_testing_cros_settings.h"
#include "chrome/browser/ash/settings/stub_cros_settings_provider.h"
#include "chromeos/ash/components/policy/device_local_account/device_local_account_type.h"
#include "chromeos/ash/components/settings/cros_settings_names.h"
#include "chromeos/dbus/power/power_manager_client.h"
#include "chromeos/dbus/tpm_manager/tpm_manager_client.h"
#include "components/policy/core/common/cloud/cloud_policy_client.h"
#include "components/policy/core/common/cloud/mock_cloud_policy_client.h"
#include "components/prefs/testing_pref_service.h"
#include "components/session_manager/core/session_manager.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/user_activity/user_activity_detector.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/events/platform/platform_event_source.h"
#include "ui/events/platform_event.h"

namespace policy {

namespace {

constexpr base::TimeDelta kDefaultStatusUploadDelay = base::Hours(1);
constexpr base::TimeDelta kMinImmediateUploadInterval = base::Seconds(10);
constexpr base::TimeDelta kMinimumScreenshotIdlenessCutoff = base::Minutes(5);

// Using a DeviceStatusCollector to have a concrete StatusCollector, but the
// exact type doesn't really matter, as it is being mocked.
class MockDeviceStatusCollector : public DeviceStatusCollector {
 public:
  explicit MockDeviceStatusCollector(PrefService* local_state)
      : DeviceStatusCollector(local_state, nullptr, nullptr, nullptr) {}
  MOCK_METHOD1(GetStatusAsync, void(StatusCollectorCallback));

  MOCK_METHOD0(OnSubmittedSuccessfully, void());

  // Explicit mock implementation declared here, since gmock::Invoke can't
  // handle returning non-moveable types like scoped_ptr.
  std::unique_ptr<DeviceLocalAccount> GetAutoLaunchedKioskSessionInfo()
      override {
    return std::make_unique<DeviceLocalAccount>(
        DeviceLocalAccountType::kKioskApp,
        policy::DeviceLocalAccount::EphemeralMode::kUnset, "account_id",
        "app_id", "update_url");
  }
};

}  // namespace

class StatusUploaderTest : public testing::Test {
 public:
  StatusUploaderTest() : task_runner_(new base::TestSimpleTaskRunner()) {
    DeviceStatusCollector::RegisterPrefs(prefs_.registry());
  }

  void SetUp() override {
    // Required for `DeviceStatusCollector`.
    chromeos::PowerManagerClient::InitializeFake();
    chromeos::TpmManagerClient::InitializeFake();
    client_.SetDMToken("dm_token");
    collector_ = std::make_unique<MockDeviceStatusCollector>(&prefs_);

    // Keep a pointer to the mock collector because collector_ gets cleared
    // when it is passed to the StatusUploader constructor.
    collector_ptr_ = collector_.get();
  }

  void TearDown() override {
    content::RunAllTasksUntilIdle();
    chromeos::TpmManagerClient::Shutdown();
    chromeos::PowerManagerClient::Shutdown();
  }

  // Given a pending task to upload status, runs the task and returns the
  // callback waiting to get device status / session status. The status upload
  // task will be blocked until the test code calls that callback.
  StatusCollectorCallback CollectStatusCallback() {
    // Running the task should pass a callback into
    // GetStatusAsync. We'll grab this callback.
    EXPECT_TRUE(task_runner_->HasPendingTask());
    StatusCollectorCallback status_callback;
    EXPECT_CALL(*collector_ptr_, GetStatusAsync)
        .WillOnce(MoveArg<0>(&status_callback));
    task_runner_->RunPendingTasks();

    return status_callback;
  }

  // Given a pending task to upload status, mocks out a server response.
  void RunPendingUploadTaskAndCheckNext(const StatusUploader& uploader,
                                        base::TimeDelta expected_delay,
                                        bool upload_success) {
    StatusCollectorCallback status_callback = CollectStatusCallback();

    // Running the status collected callback should trigger
    // CloudPolicyClient::UploadDeviceStatus.
    CloudPolicyClient::ResultCallback callback;
    EXPECT_CALL(client_, UploadDeviceStatus).WillOnce(MoveArg<3>(&callback));

    // Send some "valid" (read: non-nullptr) device/session data to the
    // callback in order to simulate valid status data.
    StatusCollectorParams status_params;
    std::move(status_callback).Run(std::move(status_params));

    // Make sure no status upload is queued up yet (since an upload is in
    // progress).
    EXPECT_FALSE(task_runner_->HasPendingTask());

    // StatusUpdater is only supposed to tell DeviceStatusCollector to clear its
    // caches if the status upload succeeded.
    EXPECT_CALL(*collector_ptr_, OnSubmittedSuccessfully())
        .Times(upload_success ? 1 : 0);

    // Now invoke the response.
    std::move(callback).Run(
        upload_success ? CloudPolicyClient::Result(DM_STATUS_SUCCESS)
                       : CloudPolicyClient::Result(DM_STATUS_REQUEST_FAILED));

    // Now that the previous request was satisfied, a task to do the next
    // upload should be queued.
    EXPECT_EQ(1U, task_runner_->NumPendingTasks());

    CheckPendingTaskDelay(uploader, expected_delay,
                          task_runner_->NextPendingTaskDelay());
  }

  void CheckPendingTaskDelay(const StatusUploader& uploader,
                             base::TimeDelta expected_delay,
                             base::TimeDelta task_delay) {
    // The next task should be scheduled sometime between |last_upload| +
    // |expected_delay| and |now| + |expected_delay|.
    base::Time now = base::Time::NowFromSystemTime();
    base::Time next_task = now + task_delay;

    EXPECT_LE(next_task, now + expected_delay);
    EXPECT_GE(next_task, uploader.last_upload() + expected_delay);
  }

  std::unique_ptr<StatusUploader> CreateStatusUploader() {
    return std::make_unique<StatusUploader>(&client_, std::move(collector_),
                                            task_runner_,
                                            kDefaultStatusUploadDelay);
  }

  void MockUserInput() {
    ui::MouseEvent e(ui::EventType::kMousePressed, gfx::Point(), gfx::Point(),
                     ui::EventTimeForNow(), 0, 0);
    const ui::PlatformEvent& native_event = &e;
    ui::UserActivityDetector::Get()->DidProcessEvent(native_event);
  }

  content::BrowserTaskEnvironment task_environment_{
      content::BrowserTaskEnvironment::TimeSource::MOCK_TIME};
  scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
  ash::ScopedTestingCrosSettings scoped_testing_cros_settings_;
  std::unique_ptr<MockDeviceStatusCollector> collector_;
  raw_ptr<MockDeviceStatusCollector, DanglingUntriaged> collector_ptr_;
  MockCloudPolicyClient client_;
  TestingPrefServiceSimple prefs_;
  // This property is required to instantiate the session manager, a singleton
  // which is used by the device status collector.
  session_manager::SessionManager session_manager_;
};

TEST_F(StatusUploaderTest, BasicTest) {
  EXPECT_FALSE(task_runner_->HasPendingTask());
  auto uploader = CreateStatusUploader();
  EXPECT_EQ(1U, task_runner_->NumPendingTasks());
  // On startup, first update should happen in 1 minute.
  EXPECT_EQ(base::Minutes(1), task_runner_->NextPendingTaskDelay());
}

TEST_F(StatusUploaderTest, DifferentFrequencyAtStart) {
  const base::TimeDelta new_delay = kDefaultStatusUploadDelay * 2;

  scoped_testing_cros_settings_.device_settings()->SetInteger(
      ash::kReportUploadFrequency, new_delay.InMilliseconds());
  EXPECT_FALSE(task_runner_->HasPendingTask());
  auto uploader = CreateStatusUploader();
  ASSERT_EQ(1U, task_runner_->NumPendingTasks());
  // On startup, first update should happen in 1 minute.
  EXPECT_EQ(base::Minutes(1), task_runner_->NextPendingTaskDelay());

  // Second update should use the delay specified in settings.
  RunPendingUploadTaskAndCheckNext(*uploader, new_delay,
                                   true /* upload_success */);
}

TEST_F(StatusUploaderTest, ResetTimerAfterStatusCollection) {
  auto uploader = CreateStatusUploader();
  RunPendingUploadTaskAndCheckNext(*uploader, kDefaultStatusUploadDelay,
                                   true /* upload_success */);

  // Handle this response also, and ensure new task is queued.
  RunPendingUploadTaskAndCheckNext(*uploader, kDefaultStatusUploadDelay,
                                   true /* upload_success */);

  // Now that the previous request was satisfied, a task to do the next
  // upload should be queued again.
  EXPECT_EQ(1U, task_runner_->NumPendingTasks());
}

TEST_F(StatusUploaderTest, ResetTimerAfterFailedStatusCollection) {
  auto uploader = CreateStatusUploader();

  // Running the queued task should pass a callback into
  // GetStatusAsync. We'll grab this callback and send nullptrs
  // to it in order to simulate failure to get status.
  EXPECT_EQ(1U, task_runner_->NumPendingTasks());
  StatusCollectorCallback status_callback;
  EXPECT_CALL(*collector_ptr_, GetStatusAsync)
      .WillOnce(MoveArg<0>(&status_callback));
  task_runner_->RunPendingTasks();

  // Running the callback should trigger StatusUploader::OnStatusReceived, which
  // in turn should recognize the failure to get status and queue another status
  // upload.
  StatusCollectorParams status_params;
  status_params.device_status.reset();
  status_params.session_status.reset();
  status_params.child_status.reset();
  std::move(status_callback).Run(std::move(status_params));
  EXPECT_EQ(1U, task_runner_->NumPendingTasks());

  // Check the delay of the queued upload
  CheckPendingTaskDelay(*uploader, kDefaultStatusUploadDelay,
                        task_runner_->NextPendingTaskDelay());
}

TEST_F(StatusUploaderTest, ResetTimerAfterUploadError) {
  auto uploader = CreateStatusUploader();

  // Simulate upload error
  RunPendingUploadTaskAndCheckNext(*uploader, kDefaultStatusUploadDelay,
                                   false /* upload_success */);

  // Now that the previous request was satisfied, a task to do the next
  // upload should be queued again.
  EXPECT_EQ(1U, task_runner_->NumPendingTasks());
}

TEST_F(StatusUploaderTest, ResetTimerAfterUnregisteredClient) {
  auto uploader = CreateStatusUploader();

  client_.SetDMToken("");
  EXPECT_FALSE(client_.is_registered());

  StatusCollectorCallback status_callback = CollectStatusCallback();

  // Running the status collected callback should trigger
  // CloudPolicyClient::UploadDeviceStatus.
  CloudPolicyClient::ResultCallback callback;
  EXPECT_CALL(client_, UploadDeviceStatus).WillOnce(MoveArg<3>(&callback));

  // Send some "valid" (read: non-nullptr) device/session data to the
  // callback in order to simulate valid status data.
  StatusCollectorParams status_params;
  std::move(status_callback).Run(std::move(status_params));

  // Make sure no status upload is queued up yet (since an upload is in
  // progress).
  EXPECT_FALSE(task_runner_->HasPendingTask());

  // No successful submit will happen if not registered.
  EXPECT_CALL(*collector_ptr_, OnSubmittedSuccessfully()).Times(0);

  // Now invoke the response.
  std::move(callback).Run(
      CloudPolicyClient::Result(CloudPolicyClient::NotRegistered()));

  // A task to try again should be queued.
  ASSERT_EQ(1U, task_runner_->NumPendingTasks());

  CheckPendingTaskDelay(*uploader, kDefaultStatusUploadDelay,
                        task_runner_->NextPendingTaskDelay());
}

TEST_F(StatusUploaderTest, ChangeFrequency) {
  auto uploader = CreateStatusUploader();
  // Change the frequency. The new frequency should be reflected in the timing
  // used for the next callback.
  const base::TimeDelta new_delay = kDefaultStatusUploadDelay * 2;
  scoped_testing_cros_settings_.device_settings()->SetInteger(
      ash::kReportUploadFrequency, new_delay.InMilliseconds());
  RunPendingUploadTaskAndCheckNext(*uploader, new_delay,
                                   true /* upload_success */);
}

TEST_F(StatusUploaderTest, ScreenshotUploadAllowOnlyAfterCutoffTime) {
  auto uploader = CreateStatusUploader();
  // Should allow data upload before there is user input.
  EXPECT_TRUE(uploader->IsScreenshotAllowed());

  MockUserInput();
  EXPECT_FALSE(uploader->IsScreenshotAllowed());

  MockUserInput();
  task_environment_.AdvanceClock(kMinimumScreenshotIdlenessCutoff -
                                 base::Seconds(1));
  EXPECT_FALSE(uploader->IsScreenshotAllowed());

  // Screenshot is allowed again after a period of inactivity
  MockUserInput();
  task_environment_.AdvanceClock(kMinimumScreenshotIdlenessCutoff +
                                 base::Seconds(1));
  EXPECT_TRUE(uploader->IsScreenshotAllowed());
}

TEST_F(StatusUploaderTest, NoUploadAfterVideoCapture) {
  auto uploader = CreateStatusUploader();
  // Should allow data upload before there is video capture.
  EXPECT_TRUE(uploader->IsScreenshotAllowed());

  // Now mock video capture, and no session data should be allowed.
  MediaCaptureDevicesDispatcher::GetInstance()->OnMediaRequestStateChanged(
      0, 0, 0, GURL("http://www.google.com"),
      blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE,
      content::MEDIA_REQUEST_STATE_OPENING);
  base::RunLoop().RunUntilIdle();
  EXPECT_FALSE(uploader->IsScreenshotAllowed());
}

TEST_F(StatusUploaderTest, ScheduleImmediateStatusUpload) {
  EXPECT_FALSE(task_runner_->HasPendingTask());
  auto uploader = CreateStatusUploader();
  EXPECT_EQ(1U, task_runner_->NumPendingTasks());

  // On startup, first update should happen in 1 minute.
  EXPECT_EQ(base::Minutes(1), task_runner_->NextPendingTaskDelay());

  // Schedule an immediate status upload.
  uploader->ScheduleNextStatusUploadImmediately();
  EXPECT_EQ(2U, task_runner_->NumPendingTasks());
  CheckPendingTaskDelay(*uploader, base::TimeDelta(),
                        task_runner_->FinalPendingTaskDelay());
}

TEST_F(StatusUploaderTest, ScheduleImmediateStatusUploadConsecutively) {
  EXPECT_FALSE(task_runner_->HasPendingTask());
  auto uploader = CreateStatusUploader();
  EXPECT_EQ(1U, task_runner_->NumPendingTasks());

  // On startup, first update should happen in 1 minute.
  EXPECT_EQ(base::Minutes(1), task_runner_->NextPendingTaskDelay());

  // Schedule an immediate status upload and run it.
  uploader->ScheduleNextStatusUploadImmediately();
  RunPendingUploadTaskAndCheckNext(*uploader, kDefaultStatusUploadDelay,
                                   true /* upload_success */);

  // Schedule the next one and check that it was scheduled after
  // kMinImmediateUploadInterval of the last upload.
  uploader->ScheduleNextStatusUploadImmediately();
  EXPECT_EQ(2U, task_runner_->NumPendingTasks());
  CheckPendingTaskDelay(*uploader, kMinImmediateUploadInterval,
                        task_runner_->FinalPendingTaskDelay());
}

}  // namespace policy